给WORDPRESS自动添加关键字和描述,无乱码,无需插件

将以下代码加入你的主题的header.php文件之中,放入<title>…<title>之后

<?php
//————-关键字,描述代码—————-
//自动将日志内容截取输出为描述,自动将tag输出为关键字,完美无乱码
//还可在后台发表时自定义字段(Custom Field)中手动添加关键字.
if (!function_exists(‘utf8Substr’)) {
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);
}
}
if (is_home()){
    //首页关键字和描述
    $description = “首页描述.”;
    $keywords = “首页关键词”} elseif (is_single()){
    if ($post->post_excerpt) {
        $description  = $post->post_excerpt;
    } else {
   if(preg_match(‘/<p>(.*)</p>/iU’,trim(strip_tags($post->post_content,”<p>”)),$result)){
    $post_content = $result[‘1’];
   } else {
    $post_content_r = explode(“n”,trim(strip_tags($post->post_content)));
    $post_content = $post_content_r[‘0’];
   }
         $description = utf8Substr($post_content,0,220);  
  }

    $keywords = “”;     
    $tags = wp_get_post_tags($post->ID);
    foreach ($tags as $tag ) {
        $keywords = $keywords . $tag->name . “,”;
    }

}

?>
<meta name=”description” content=”<?php echo trim($description); ?>”/>
<meta name=”keywords” content=”<?php echo rtrim($keywords,’,’);?>

<?php $key=”keywords”; echo get_post_meta($post->ID, $key, true); ?>”/>

发表评论

电子邮件地址不会被公开。 必填项已用*标注