1. 程式人生 > >不用外掛給wordpress自動新增關鍵字和描述

不用外掛給wordpress自動新增關鍵字和描述

在wordpress後臺編輯header.php檔案,在<head>標籤裡面,一般放在<title>標籤的下面比較美觀,加入如下程式碼。

<pre name="code" class="html"><?php
$keywords = get_bloginfo('name');
$description = get_bloginfo('description', 'display');
if (is_home()){
    $keywords = get_bloginfo('name');
    $description = get_bloginfo('description', 'display');
}
elseif (is_single()){
    $keywords = get_post_meta($post->ID, "keywords", true);
    if($keywords == ""){
        $tags = wp_get_post_tags($post->ID);
        foreach ($tags as $tag){
            $keywords = $keywords.$tag->name.",";
        }
        $keywords = rtrim($keywords, ', ');
    }
    $description = get_post_meta($post->ID, "description", true);
    if($description == ""){
        if($post->post_excerpt){
            $description = $post->post_excerpt;
        }else{
            $description = mb_strimwidth(strip_tags(apply_filters('the_content',$post->post_content)),0,200);
        }
    }
}
elseif (is_page()){
    $keywords = get_post_meta($post->ID, "keywords", true);
    if($keywords == ""){
        $keywords = get_bloginfo('title');
    }
    $description = get_post_meta($post->ID, "description", true);
    if($description == ""){
        if($post->post_excerpt){
            $description = $post->post_excerpt;
        }else{
            $description = mb_strimwidth(strip_tags(apply_filters('the_content',$post->post_content)),0,200);
        }
    }
}
elseif (is_category()){
    $keywords = single_cat_title('', false);
    $description = category_description();
}
elseif (is_tag()){
    $keywords = single_tag_title('', false);
    $description = tag_description();
}
$keywords = trim(strip_tags($keywords));
$description = trim(strip_tags($description));
?>
<meta name="keywords" content="<?php echo $keywords; ?>" />
<meta name="description" content="<?php echo $description; ?>" />