WordPress免插件增加seo信息,兼容Open Graph、Twitter Card、Schema.org结构化数据

有一个需求,需要有针对性的对所有类型页面增加seo信息,由于有一些插件创建了新的post type,因此很多seo信息无法输出,再加上还要兼容wpjam的seo信息,本来想着用插件,但是就这么简单的活儿装个插件比较费劲,于是写完让ai重构了下,基本满足需求了,各位大神用的时候可能需要改一改。

<?php
/**
 * WordPress SEO优化 - 添加Open Graph标签和关键词支持
 * 简化图片处理逻辑,适配百度搜索引擎和社交媒体展示需求
 */

class SEO_Optimization {
    // 存储SEO数据的数组
    private $seo_data = array(
        'title' => '',
        'type' => 'website',
        'url' => '',
        'site_name' => '',
        'description' => '',
        'image' => '',
        'keywords' => '',
        'baidu_logo' => '' // 百度专属logo (200*133)
    );

    public function __construct() {
        // 初始化站点名称
        $this->seo_data['site_name'] = get_bloginfo('name');
        
        // 初始化百度专属logo (200*133) - 从子主题images目录获取
        $this->seo_data['baidu_logo'] = ZKEEV_STATIC. '/imag/logo-200x133.png';
        
        // 添加动作钩子
        add_action('wp_head', array($this, 'add_open_graph_tags'), 5);
    }

    /**
     * 主函数:添加Open Graph标签和SEO关键词
     */
    public function add_open_graph_tags() {
        // 获取站点关键词
        $site_keywords = get_option('site_seo_keywords', '');
        
        // 根据页面类型设置SEO数据
        $this->set_seo_data_by_page_type($site_keywords);
        
        // 输出SEO标签
        $this->output_seo_tags();
    }

    /**
     * 根据页面类型设置SEO数据
     */
    private function set_seo_data_by_page_type($site_keywords) {
        if (is_front_page()) {    
            $this->set_front_page_seo($site_keywords);
        }
        elseif (is_home()) {
            $this->set_blog_page_seo($site_keywords);
        }
        elseif (is_singular()) {
            $this->set_singular_seo();
        }
        elseif (is_archive()) {
            $this->set_archive_seo();
        }
        
        // 对所有页面类型应用WPJAM_SEO数据(博客页面除外,已在内部处理)
        if (!is_home() && class_exists('WPJAM_SEO')) {
            $wpjam_title = WPJAM_SEO::get_value('title', false);
            $wpjam_description = WPJAM_SEO::get_value('description', false);
            $wpjam_keywords = WPJAM_SEO::get_value('keywords', false);
            
            $this->apply_wpjam_seo_data($wpjam_title, $wpjam_description, $wpjam_keywords);
        }
    }
    
    /**
     * 应用WPJAM_SEO数据
     */
    private function apply_wpjam_seo_data($wpjam_title, $wpjam_description, $wpjam_keywords) {
        $this->seo_data['title'] = $wpjam_title ?: $this->seo_data['title'];
        $this->seo_data['description'] = $wpjam_description ?: $this->seo_data['description'];
        $this->seo_data['keywords'] = $wpjam_keywords ?: $this->seo_data['keywords'];
    }

    /**
     * 设置静态首页的SEO数据
     */
    private function set_front_page_seo($site_keywords) {
        $this->seo_data['title'] = get_bloginfo('name') . ' – ' . get_bloginfo('description');
        $this->seo_data['description'] = get_bloginfo('description');
        $this->seo_data['url'] = home_url();
        $this->seo_data['keywords'] = $site_keywords;
        
        // 首页使用百度专属logo
        $this->seo_data['image'] = $this->seo_data['baidu_logo'];
    }

    /**
     * 设置博客页面的SEO数据
     */
    private function set_blog_page_seo($site_keywords) {
        $blog_page_id = get_option('page_for_posts');
        
        if (!$blog_page_id) {
            // 若未设置博客页面,使用默认逻辑
            $this->seo_data['title'] = get_bloginfo('name') . ' – ' . get_bloginfo('description');
            $this->seo_data['description'] = get_bloginfo('description');
            $this->seo_data['url'] = home_url();
            $this->seo_data['keywords'] = $site_keywords;
        } else {
            // 获取博客页面的SEO数据
            $this->set_page_seo_data($blog_page_id, $site_keywords);
        }
        
        // 博客页面图片:优先使用特色图像,否则使用百度logo
        $this->seo_data['image'] = has_post_thumbnail($blog_page_id) 
            ? get_the_post_thumbnail_url($blog_page_id, 'full') 
            : $this->seo_data['baidu_logo'];
    }

    /**
     * 设置单页内容的SEO数据
     */
    private function set_singular_seo() {
        global $post;
        
        $this->seo_data['title'] = get_the_title() . ' – ' . get_bloginfo('name');
        $this->seo_data['url'] = get_permalink();
        
        // 单页内容图片:优先使用缩略图,否则使用百度logo
        $this->seo_data['image'] = has_post_thumbnail() 
            ? get_the_post_thumbnail_url($post->ID, 'full') 
            : $this->seo_data['baidu_logo'];
        
        // 获取或生成描述
        $this->seo_data['description'] = $this->generate_post_description($post);
        
        // 根据内容类型设置og:type和关键词
        $post_type = get_post_type();
        if ($post_type === 'post') {
            $this->seo_data['type'] = 'article';
            $this->seo_data['keywords'] = $this->get_post_keywords($post);
        } 
        elseif ($post_type === 'ot_portfolio') {
            $this->seo_data['type'] = 'website';
            $this->seo_data['keywords'] = $this->get_portfolio_keywords($post);
        }
    }

    /**
     * 设置存档页面的SEO数据
     */
    private function set_archive_seo() {
        $this->seo_data['title'] = single_cat_title('', false) . ' – ' . get_bloginfo('name');
        $this->seo_data['description'] = category_description();
        $this->seo_data['url'] = get_category_link(get_queried_object_id());
        
        // 使用存档名称作为关键词
        $term = get_queried_object();
        if ($term && isset($term->name)) {
            $this->seo_data['keywords'] = $term->name;
        }
        
        // 存档页面图片:使用百度logo
        $this->seo_data['image'] = $this->seo_data['baidu_logo'];
    }

    /**
     * 生成文章描述
     */
    private function generate_post_description($post) {
        if (has_excerpt()) {
            return strip_tags(get_the_excerpt());
        } else {
            $content = strip_tags($post->post_content);
            $content = str_replace(array("\r", "\n", "\t"), ' ', $content);
            $content = trim(preg_replace('/\s+/', ' ', $content));
            return mb_substr($content, 0, 200, 'UTF-8');
        }
    }

    /**
     * 获取文章关键词
     */
    private function get_post_keywords($post) {
        $tags = get_the_tags();
        $categories = get_the_category();
        $keywords = array();
        
        if ($tags) {
            foreach ($tags as $tag) {
                $keywords[] = $tag->name;
            }
        }
        
        if ($categories) {
            foreach ($categories as $category) {
                $keywords[] = $category->name;
            }
        }
        
        // 合并并去重关键词,取前4个
        $keywords = array_unique($keywords);
        return implode(', ', array_slice($keywords, 0, 4));
    }

    /**
     * 获取作品集关键词
     */
    private function get_portfolio_keywords($post) {
        if (!taxonomy_exists('portfolio_tag') || $post->post_type !== 'ot_portfolio') {
            return '';
        }
        
        $tags = get_the_terms($post->ID, 'portfolio_tag');
        
        if ($tags && !is_wp_error($tags)) {
            $tag_names = array();
            foreach ($tags as $tag) {
                $tag_names[] = $tag->name;
            }
            return implode(', ', array_slice($tag_names, 0, 4));
        }
        
        return '';
    }

    /**
     * 设置页面SEO数据(通用方法)
     */
    private function set_page_seo_data($page_id, $site_keywords) {
        // 获取页面基础数据
        $page_title = get_the_title($page_id);
        $page_url = get_permalink($page_id);
        
        // 获取页面自定义SEO元数据
        $page_description = get_post_meta($page_id, 'seo_description', true);
        $page_keywords = get_post_meta($page_id, 'seo_keywords', true);
        
        // 设置SEO数据
        $this->seo_data['title'] = $page_title ? $page_title . ' – ' . get_bloginfo('name') : get_bloginfo('name');
        $this->seo_data['description'] = $page_description ?: get_bloginfo('description');
        $this->seo_data['url'] = $page_url;
        $this->seo_data['keywords'] = $page_keywords ?: $site_keywords;
    }

    /**
     * 输出SEO标签
     */
    private function output_seo_tags() {
        // 移动适配标签
        echo '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
        echo '<meta name="mobile-agent" content="format=html5; url=' . esc_url($this->seo_data['url']) . '">';
        
        // 禁止百度转码
        echo '<meta http-equiv="Cache-Control" content="no-transform">';
        echo '<meta http-equiv="Cache-Control" content="no-siteapp">';
        
        if (!empty($this->seo_data['title'])) {
            // Open Graph标签
            echo '<meta property="og:title" content="' . esc_attr($this->seo_data['title']) . '">';
            echo '<meta property="og:type" content="' . esc_attr($this->seo_data['type']) . '">';
            echo '<meta property="og:url" content="' . esc_url($this->seo_data['url']) . '">';
            echo '<meta property="og:site_name" content="' . esc_attr($this->seo_data['site_name']) . '">';
            
            if (!empty($this->seo_data['description'])) {
                echo '<meta property="og:description" content="' . esc_attr($this->seo_data['description']) . '">';
            }
            
            if (!empty($this->seo_data['image'])) {
                echo '<meta property="og:image" content="' . esc_url($this->seo_data['image']) . '">';
                
                // 针对百度优化:添加百度logo的特定标签
                if ($this->seo_data['image'] === $this->seo_data['baidu_logo']) {
                    echo '<link rel="search" type="image/x-icon" href="' . esc_url($this->seo_data['baidu_logo']) . '" title="' . esc_attr($this->seo_data['site_name']) . '">';
                    echo '<meta name="msapplication-TileImage" content="' . esc_url($this->seo_data['baidu_logo']) . '">';
                }
                
                // 添加图片尺寸信息
                if ($this->seo_data['image'] === $this->seo_data['baidu_logo']) {
                    echo '<meta property="og:image:width" content="200">';
                    echo '<meta property="og:image:height" content="133">';
                } else {
                    echo '<meta property="og:image:width" content="1200">';
                    echo '<meta property="og:image:height" content="630">';
                }
            }
            
            // Twitter Card标签
            echo '<meta name="twitter:card" content="summary_large_image">';
            echo '<meta name="twitter:title" content="' . esc_attr($this->seo_data['title']) . '">';
            
            if (!empty($this->seo_data['description'])) {
                echo '<meta name="twitter:description" content="' . esc_attr($this->seo_data['description']) . '">';
            }
            
            if (!empty($this->seo_data['image'])) {
                echo '<meta name="twitter:image" content="' . esc_url($this->seo_data['image']) . '">';
            }
            
            // 输出关键词
            if (!empty($this->seo_data['keywords'])) {
                echo '<meta property="og:keywords" content="' . esc_attr($this->seo_data['keywords']) . '">';
                echo '<meta name="keywords" content="' . esc_attr($this->seo_data['keywords']) . '">';
            }
            
            // 基础SEO标签
            echo '<title>' . esc_html($this->seo_data['title']) . '</title>';
            
            if (!empty($this->seo_data['description'])) {
                echo '<meta name="description" content="' . esc_attr($this->seo_data['description']) . '">';
            }
            
            // Schema.org结构化数据
            echo '<script type="application/ld+json">';
            echo '{';
            echo '  "@context": "https://schema.org",';
            echo '  "@type": "' . ($this->seo_data['type'] === 'article' ? 'Article' : 'WebPage') . '",';
            echo '  "headline": "' . esc_js($this->seo_data['title']) . '",';
            echo '  "url": "' . esc_url($this->seo_data['url']) . '",';
            
            if (!empty($this->seo_data['description'])) {
                echo '  "description": "' . esc_js($this->seo_data['description']) . '",';
            }
            
            if (!empty($this->seo_data['image'])) {
                echo '  "image": {';
                echo '    "@type": "ImageObject",';
                echo '    "url": "' . esc_url($this->seo_data['image']) . '",';
                
                if ($this->seo_data['image'] === $this->seo_data['baidu_logo']) {
                    echo '    "width": 200,';
                    echo '    "height": 133';
                } else {
                    echo '    "width": 1200,';
                    echo '    "height": 630';
                }
                
                echo '  },';
            }
            
            echo '  "publisher": {';
            echo '    "@type": "Organization",';
            echo '    "name": "' . esc_js($this->seo_data['site_name']) . '"';
            echo '  }';
            echo '}';
            echo '</script>';
        }
    }
}

// 实例化SEO优化类
new SEO_Optimization();



 

本文作者:ZKCOI

文章名称:WordPress免插件增加seo信息,兼容Open Graph、Twitter Card、Schema.org结构化数据

文章链接:https://www.zkcoi.com/365up/program/4293.html

本站资源仅供个人学习和交流,如若转载,请注明出处,详见《免责声明》

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
ZKCOIZKCOI
2025最新deepseek券商分析报告合集,共84份!
上一篇 2025年3月9日 下午6:51
下一篇 2025年6月19日 下午5:05

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系博主

立即联系
一般有空就回复

qrcode_web

微信扫码联系我

insert_link 友情链接
分享本页
返回顶部