WordPress 网站添加关键词 keywords 和描述 description

wordPress是世界上最受欢迎的内容管理系统,占据了三分之一的份额。然而, WordPress本身缺少一些SEO功能,如Keywords和Description标签。

WordPress网站SEO

尽管有几个功能非常完善的SEO插件,如Yoast SEO,要付费才能使用高级功能。
而且,这些插件大多较为臃肿,增加服务器额外的运算压力。

在网络上查询一番,找到以下方法,可以一定程度上实现keywordsdescription内容的自动导入。

亲测有效

代码

需要通过Wordpress把下面代码添加到 header.php主题文件中。

<?php $options = get_option('deve_options'); ?> 
    <?php
    $keywords = 'xxxx博客';
    $description = '专注分享日常工作踩坑记录';
        //文章页
     if (is_single()){
        //自定义栏目添加关键字和描述
        $single_keywords = get_post_meta($post->ID, "keywords", true);
        $description = get_post_meta($post->ID, "description", true);
        //如果没设置自定义关键字,将使用标签作为关键字
        if($single_keywords == ""){
            $tags = wp_get_post_tags($post->ID);
            foreach ($tags as $tag){
                $single_keywords = $single_keywords.$tag->name.",";
            }
            //去掉关键字前后的空白
            $single_keywords = rtrim($single_keywords, ', ');
        }
        ///如果文章关键字不为空
        if($single_keywords){
            $keywords = $single_keywords;
        }
        //自定义描述如果为空,将使用文章中的100个字作为描述
        if($description == ""){
            if($post->post_excerpt){
                $description = $post->post_excerpt;
            }else{
                $description = mb_strimwidth(strip_tags(apply_filters('the_content',$post->post_content)),0,200);
            }
        }
    }
    //页面,添加自定义栏目keywords和description(关键字和描述)。
    elseif (is_page()){
        $keywords = get_post_meta($post->ID, "keywords", true);
        $description = get_post_meta($post->ID, "description", true);
    }
    //分类页,使用分类名作为关键字,分类描述作为文章描述。
    elseif (is_category()){
        $keywords = single_cat_title('', false);
        $description = category_description();
    }
    //标签页,使用标签名作为关键字,标签描述作为文章描述。
    elseif (is_tag()){
        $keywords = single_tag_title('', false);
        $description = tag_description();
    }
    //去掉两段空格
    $keywords = trim(strip_tags($keywords));
    $description = trim(strip_tags($description));
    ?>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<meta name="description" content="<?php echo $description; ?>" />

根据wordpress建站的页面Pages或Posts特点,分别将标签Tags或Category等作为页面的关键字和描述,以优化搜索引擎索引效率和准确度的效果。

参考资料

1.https://maolego.com/291.html