以下代碼實現的是以標籤為關鍵詞;以摘要為描述,如果沒有填寫摘要,那就自動截取文章前 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 行的內容需要根據你的網站進行修改。