WordPress添加关键词和描述标签

关键词和描述标签作为SEO的基础配置,在wordpress中没有默认添加,这里记录一下在Wordpress中自动添加关键词和描述标签的方法。

一、实现代码

实现思路是使用标签来作为关键词,使用文章摘要作为页面描述,找到使用主题的functions.php文件,添加以下代码即可实现。

/**
 * 添加SEO相关的Keywords和Description标签
 */
function add_seo_meta_tags() {
    if (is_home()) {
        $tags = get_tags([
            'number' => 15,
            'orderby' => 'count',
            'order' => 'DESC'
        ]);
        $tags = array_map(function ($item) {
            return $item->name;
        }, $tags);
        if (count($tags) > 0) {
            ?>
            <meta name="keywords" content="<?php echo get_bloginfo('name'); ?>,<?php echo implode(',', $tags); ?>">
            <?php
        }
        ?>
            <meta name="description" content="<?php echo get_bloginfo('description'); ?>">
        <?php
    } else if (is_category() || is_tag()) {
        ?>
            <meta name="keywords" content="<?php echo single_cat_title(); ?>">
            <meta name="description" content="<?php echo strip_tags(category_description()); ?>">
        <?php
    } else if (is_singular()) {
        ?>
            <meta name="description" content="<?php echo strip_tags(get_the_excerpt()); ?>">
        <?php

        $tags = array_map(function ($item) {
            return $item->name;
        }, get_the_tags() ?: []);
        if (count($tags) > 0) {
            ?>
                <meta name="keywords" content="<?php echo implode(',', $tags); ?>">
            <?php
        }
    }
}
add_action( 'wp_head', 'add_seo_meta_tags' );

二、使用的前置要求

请注意,需要保证主题的header.php调用过wp_head()函数,类似下面:

<!DOCTYPE html>
<html <?php language_attributes(); ?> class="no-js">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">

<?php wp_head(); ?>
</head>

OK,这样我们就给所有页面都添加上关键词和描述标签了~

相关链接:

  1. wordpress关于meta标签的说明
文章标签