以下代碼實現的是以標籤為關鍵詞;以摘要為描述,如果沒有填寫摘要,那就自動截取文章前 200 字為描述

代碼實現 WordPress 自動關鍵詞與描述:

以下代碼放到你的主題下 funtions.php 的最後一個 ?> 前:

  1. //自動關鍵詞與描述
  2. function get_cats_name() {
  3. $allcats=get_categories();
  4. foreach ($allcats as $category)
  5. {
  6. $keywords[] = $category->cat_name;
  7. }
  8. return $keywords;
  9. }
  10. // utf8 substr
  11. function utf8Substr($str, $from, $len) {
  12. return preg_replace('#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$from.'}'.
  13. '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len.'}).*#s',
  14. '$1',$str);
  15. }
  16. // Meta SEO
  17. function meta_SEO() {
  18. global $post;
  19. $output = '';
  20. if (is_single()){//如果是文章頁
  21. $keywords = '';
  22. $description = '';
  23. if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要為描述
  24. $description = $post->post_excerpt;
  25. $description = str_replace("
    "
    ,"",$description);
  26. $description = str_replace("
    "
    ,"",$description);
  27. $description = str_replace(""","'",$description);
  28. $description .= '...';
  29. else {//如果文章摘要不存在就截斷文章前 200 字為描述
  30. $description = utf8Substr(strip_tags($post->post_content),0,200);
  31. $description = str_replace("
    "
    ,"",$description);
  32. $description = str_replace("
    "
    ,"",$description);
  33. $description = str_replace(""","'",$description);
  34. $description .= '...';
  35. }
  36. $tags = wp_get_post_tags($post->ID);//取文章標籤
  37. foreach ($tags as $tag ) {
  38. $keywordarray[] = $tag->name;
  39. }
  40. //以文章標籤為關鍵字
  41. $keywords = implode(',',array_unique((array)$keywordarray));
  42. else {//如果不是文章頁
  43. $keywords = 'wordpress,wordpress 主題,wordpress 教程,wordpress 主題下載,wordpress 博客主題,wordpress 企業主題,wordpress 主題定製'; //在引號間寫入你博客的關鍵字用, 斷開
  44. $description = '主題貓,致力於為廣大網友提供最新最全的 wordpress 主題';//在引號間寫入你博客的簡單描述,不要過 200 字
  45. }
  46. //輸出關鍵字
  47. $output .= '<meta name="keywords" content="' . $keywords . '" />' . "
    "
    ;
  48. $output .= '<meta name="description" content="' . $description . '" />' . "
    "
    ;
  49. //輸出描述
  50. echo "$output
    "
    ;
  51. }
  52. add_action('wp_head', 'meta_SEO');//添加 meta_SEO 函數到頭部信息裏

第 43 行與第 44 行的內容需要根據你的網站進行修改。