WordPress文章页自动添加关键词和描述

WordPress小技巧又+1

Published in Mar-01-2022

在funtions文件里面加入以下代码

//自动关键词与描述caotongxue.cn
function meta_SEO() {
global $post;
$output = '';
if (is_single()){//如果是文章页
$keywords = ''; 
$description = '';
if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要为描述
$description = $post->post_excerpt;
$description = str_replace("\r\n","",$description);
$description = str_replace("\n","",$description);
$description = str_replace("\"","'",$description);
$description .= '...';
} else {//如果文章摘要不存在就截断文章前120字为描述
$description = utf8Substr(strip_tags($post->post_content),0,120);
$description = str_replace("\r\n","",$description);
$description = str_replace("\n","",$description);
$description = str_replace("\"","'",$description);
$description .= '...';
} 
$tags = wp_get_post_tags($post->ID);//取文章标签
foreach ($tags as $tag ) {
$keywordarray[] = $tag->name;
}
//以文章标签为关键字
$keywords = implode(',',array_unique((array)$keywordarray));
} else if (is_category()){
$description = strip_tags(trim(category_description()));
$keywords = single_cat_title('', false);
}else {//如果不是文章页、分类页
$keywords = '曹同学,老曹,小曹,没有故事的曹同学,博客网站,百度SEO,搜索引擎优化,个人博客'; //在引号间写入你博客的关键字用,断开
$description = '没有故事的曹同学,吉他、音乐、微信读书,没事刷刷B站知乎瞎逛,偶尔徒步登山~';//在引号间写入你博客的简单描述,不要过200字
}
//输出关键字
$output .= '<meta name="keywords" content="' . $keywords . '" />' . "\n";
$output .= '<meta name="description" content="' . $description . '" />' . "\n";
//输出描述
echo "$output";
}

然后在single.php或者header.php里面相对应的位置加入代码调用即可。

<?php echo meta_SEO(); ?>


评论4

  1. 芭比
    2年前 (2022-05-04)

    之前做主题的时候会经常用到这个

    • 曹同学 博主
      2年前 (2022-05-07)

      @芭比 你现在用的这个主题,爱了爱了 :喜极而泣:

  2. 鸟叔
    2年前 (2022-04-23)

    鸟叔来串门,通过虫洞穿梭至此,期待回访!

    • 曹同学 博主
      2年前 (2022-04-24)

      @鸟叔 欢迎鸟叔,到你网站学习

曹同学的bilibili 曹同学的知乎 曹同学的email
返回网站顶部
正在获取,请稍候...
00:00/00:00