wordpress易于使用,用来记录一些日志与发布一些内容比较方便。但是默认页面不输出关键字与摘要。当然有安装上一些SEO的插件就Ok了,但实测安装插件后台加载很慢。直接修改代码用hook 来添加进来。目前判断了主页、目录页、内容页。各自提取关联的内容填充。
方法如下:
wp-blog-header.php 添加:
require_once( ABSPATH . ‘wp-content/index.php’ );
添加后如下:
require_once( ABSPATH . ‘wp-content/index.php’ );
<?php
/**
* Loads the WordPress environment and template.
*
* @package WordPress
*/
if ( ! isset( $wp_did_header ) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname( __FILE__ ) . ‘/wp-load.php’ );
// Set up the WordPress query.
wp();
require_once( ABSPATH . ‘wp-content/index.php’ );
// Load the theme template.
require_once( ABSPATH . WPINC . ‘/template-loader.php’ );
}
红色为新添加进来的代码。
wp-content/index.php 下添加:
function get_cats_name() {
$allcats=get_categories();
foreach ($allcats as $category)
{
$keywords[] = $category->cat_name;
}
return $keywords;
}
// Meta SEO
function meta_SEO() {
global $post;
$output = ”;
if (is_single()){//如果是文章页
$keywords = ”;
$description = ”;
if ($post->post_excerpt) {//如果文章摘要存在就以文章摘要为描述
$description = $post->post_excerpt;
$description = str_replace(“\r\n”,””,$description);
$description = str_replace(“\n”,””,$description);
$description = str_replace(“\””,”\'”,$description);
$description .= ‘…’;
} else {//如果文章摘要不存在就截断文章前200字为描述
$description = mb_substr(strip_tags($post->post_content),0,200);
$description = str_replace(“\r\n”,””,$description);
$description = str_replace(“\n”,””,$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));
} elseif( is_category() ) {//如果是分类页
global $cat;
$blog_title = get_bloginfo(‘name’);
$blog_desc = get_bloginfo(‘description’);
$cat_name = single_cat_title(‘-‘,false);
//wp_list_categories();
$sub_types = get_categories(“child_of={$cat}&hide_empty=0”);
$keywords = ”;
if($sub_types)
{
foreach($sub_types as $k => $v)
{
$keywords .= $v->name.’,’;
}
}
$keywords .= $blog_title.’,’.$blog_desc;
$description = ‘分类’.$cat_name.’ ‘.$blog_title.’ ‘.$blog_desc;
} elseif( is_home() ) {//如果是主页
$blog_title = get_bloginfo(‘name’);
$blog_desc = get_bloginfo(‘description’);
$keywords = $blog_title.’-‘.$blog_desc;
$description = ‘首页 ‘.$blog_title.’-‘.$blog_desc;
} else {//其它页
$blog_title = get_bloginfo(‘name’);
$blog_desc = get_bloginfo(‘description’);
$keywords = $blog_title.’-‘.$blog_desc;;
$description = ‘其他 ‘.$blog_title.’-‘.$blog_desc;;
}
//输出关键字
$output .= ‘<meta name=”keywords” content=”‘ . $keywords . ‘” />’ . “\n”;
$output .= ‘<meta name=”description” content=”‘ . $description . ‘” />’ . “\n”;
//输出描述
echo “$output”;
}
add_action(‘wp_head’, ‘meta_SEO’);