代码实现WordPress自动关键词keywords与描述description

代码实现WordPress自动关键词keywords与描述description

以下代码实现的是以标签为关键词;以摘要为描述,如果没有填写摘要,那就自动截取文章前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("\r\n","",$description);
$description = str_replace("\n","",$description);
$description = str_replace("\"","'",$description);
$description .= '...';
} else {//如果文章摘要不存在就截断文章前200字为描述
$description = utf8Substr(strip_tags($post->post_content),0,200);
$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 {//如果不是文章页
$keywords = '3d模型,3d模型下载,免费3d模型,3d模型免费下载'; //在引号间改成你自己网站的关键字用,断开
$description = '六模素是一个3D模型素材网为设计师提供3D模型、3D贴图、光域网,六模素3DMAX模型免费下载,素材纯手工整理,找3D模型素材就上六模素3D模型素材网。';//在引号间改成你自己网站的简单描述,不要过200字
}
//输出关键字
$output .= '<meta name="keywords" content="' . $keywords . '" />' . "\n";
$output .= '<meta name="description" content="' . $description . '" />' . "\n";
//输出描述
echo "$output\n";
}
add_action('wp_head', 'meta_SEO');//添加meta_SEO函数到头部信息里

方法二:

把以下代码放到你的主题下funtions.php

// tag 转 keyword
function tag_to_keywords() {
    if ( is_single() ) {    // 文章页面
        $posttags = get_the_tags();
        if ( $posttags ) {
            foreach ( $posttags as $tag ) {
                $keywords [] = strtolower( $tag->name );
            };
            array_push( $keywords, "gelomen", "code cola", "code", "cola" );
?>
<!-- html -->
<!-- 网站关键字,用英文逗号隔开 -->
<meta name="keywords" content="<?php echo implode( ",", array_unique( $keywords ) ); ?>"/>
<!-- 网站的描述 -->
<meta name="description" content="这是个人博客网站。"/> <!-- 文章显示这个描述 -->
<?php
        }
    } else {    // 其他页面
?>
<!-- html -->
<!-- 网站关键字,用英文逗号隔开 -->
<meta name="keywords" content="展览模型,展台模型,3D展览模型,3D模型免费下载"/>
<!-- 网站的描述 -->
<meta name="description" content="展览模型,展览3dmax模型下载,3D展台模型免费下载,展会照片,展台设计效果图欣赏,效果图在线交易平台,提供全国展台搭建服务平台。"/>
<?php
    }
}
add_action('wp_head', 'tag_to_keywords');

总结:方法一要比方法二更好用。

方法一:会获取文章标签做关键词,会获文章摘要做描述。

方法二:会获取文章标签做关键词,但还有也不完美。也不会获文章摘要做描述,文章显示代码里的指定描述。