共計 2049 個字符,預計需要花費 6 分鐘才能閱讀完成。
網絡上有不少的優秀 WordPress 主題,但是因為某些原因,開發者未能充分考慮到 SEO 問題,導致不少的 WordPress 主題源代碼中只有標題,卻沒有描述(description)和關鍵詞(keyword)兩個標簽內容,為此,博主去網上查閱了一番,將解決方法記錄如下:
<?php
if (is_home() ) {?><title><?php bloginfo('name'); ?> | <?php bloginfo('description'); ?>
</title><?php } ?>
<?php if (is_search() ) {?><title> 搜索結果 | <?php bloginfo('name'); ?></title><?php } ?>
<?php if (is_single() ) {?><title><?php echo trim(wp_title('',0)); ?> | <?php bloginfo('name'); ?></title><?php } ?>
<?php if (is_page() ) {?><title><?php echo trim(wp_title('',0)); ?> | <?php bloginfo('name'); ?></title><?php } ?>
<?php if (is_category() ) {?><title><?php single_cat_title(); ?> | <?php bloginfo('name'); ?></title><?php } ?>
<?php if (is_month() ) {?><title><?php the_time('F'); ?> | <?php bloginfo('name'); ?></title><?php } ?>
<?php if (function_exists('is_tag')) {if ( is_tag() ) {?><title><?php single_tag_title("", true); ?> | <?php bloginfo('name'); ?></title><?php } ?> <?php } ?>
<?php if (is_author() ) {?><title><?php wp_title('');?> 發表的所有文章 | <?php bloginfo('name'); ?></title><?php }?>
<?php
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_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 . ",";}
}
?>
<?php echo "n"; ?>
<?php if (is_single() ) { ?>
<meta name="description" content="<?php echo trim($description); ?>" />
<meta name="keywords" content="<?php echo rtrim($keywords,','); ?>" />
<?php } ?>
<?php if (is_home() ) { ?>
<meta name="description" content="首頁描述" />
<meta name="keywords" content="首頁關鍵字" />
<?php } ?>
然后在主題目錄中新建一個 title.php 文件,將以上代碼添加到里面,然后打開 header.php 文件,調用如下代碼:
<?php include('title.php'); ?>
如此,網站的描述和關鍵字都可以正常展示了,當然,上面的代碼加了 <title> 標簽,如果只想修改 keyword、description 的話就可以將其刪除。
正文完