以下代码实现的是以标签为关键词;以摘要为描述,如果没有填写摘要,那就自动截取文章前 200 字为描述。
代码实现 WordPress 自动关键词与描述:
以下代码放到你的主题下 funtions.php 的最后一个 ?> 前:
- //自动关键词与描述
- function get_cats_name() {
- $allcats=get_categories();
- foreach ($allcats as $category)
- {
- $keywords[] = $category->cat_name;
- }
- return $keywords;
- }
- // utf8 substr
- function utf8Substr($str, $from, $len) {
- return preg_replace('#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$from.'}'.
- '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len.'}).*#s',
- '$1',$str);
- }
- // Meta SEO
- function meta_SEO() {
- global $post;
- $output = '';
- if (is_single()){//如果是文章页
- $keywords = '';
- $description = '';
- if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要为描述
- $description = $post->post_excerpt;
- $description = str_replace("
","",$description); - $description = str_replace("
","",$description); - $description = str_replace(""","'",$description);
- $description .= '...';
- } else {//如果文章摘要不存在就截断文章前 200 字为描述
- $description = utf8Substr(strip_tags($post->post_content),0,200);
- $description = str_replace("
","",$description); - $description = str_replace("
","",$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 {//如果不是文章页
- $keywords = 'wordpress,wordpress 主题,wordpress 教程,wordpress 主题下载,wordpress 博客主题,wordpress 企业主题,wordpress 主题定制'; //在引号间写入你博客的关键字用, 断开
- $description = '主题猫,致力于为广大网友提供最新最全的 wordpress 主题';
//在引号间写入你博客的简单描述,不要过 200 字 - }
- //输出关键字
- $output .= '<meta name="keywords" content="' . $keywords . '" />' . "
"; - $output .= '<meta name="description" content="' . $description . '" />' . "
"; - //输出描述
- echo "$output
"; - }
- add_action('wp_head', 'meta_SEO');//添加 meta_SEO 函数到头部信息里
第 43 行与第 44 行的内容需要根据你的网站进行修改。