昨晚手欠,点了一下“升级Wordpress”,于是就开始了各种忙乱。

首先是在升级前没有停用正在使用的插件,老旧插件导致Wordpress的前台、后台全部白屏。
解决办法:ftp登陆上去,将插件文件夹 plugins 重命名。

其次就是各插件恢复使用后,Simple Tags 插件的作者没有提供更新,现有版本 2.0-beta9 不支持 WordPress3.2 ,导致“相关日志”无法正常工作。

言归正传,说一下如何直接用代码实现“相关日志”的功能。

  1. 打开当前所用的模版文件夹
  2. 找到functions.php
  3. 添加如下代码:


//WordPress Related Posts
$wp_rp=array(
‘limit’=>9, //相关文章数量
‘wp_rp_rss’=>true, //是否在feed 中显示相关文章
‘wp_no_rp’=>’random’, //无相关文章时的选择:text 或random(random-随机文章)
‘wp_rp_date’=>false, //显示文章发布日期
‘wp_rp_comments’=>false, //显示文章评论数
‘wp_rp_title_tag’=>’h3’, //选择相关文章标题标签(h2 ,h3 ,h4 ,p ,div)
);
function wp_get_random_posts ($limitclause=””) {
global $wpdb, $post;

$q = “SELECT ID, post_title, post_content,post_excerpt, post_date, comment_count FROM $wpdb->posts WHERE post_status = ‘publish’ AND post_type = ‘post’ AND ID != $post->ID ORDER BY RAND() $limitclause”;
return $wpdb->get_results($q);
}

function wp_get_related_posts()
{
global $wpdb, $post,$wp_rp;
$limit =$wp_rp[“limit”];
$wp_rp_title=’相关日志:’; //相关文章标题
if(!$post->ID){return;}
$now = current_time(‘mysql’, 1);
$tags = wp_get_post_tags($post->ID);

$taglist = “‘” . $tags[0]->term_id. “‘”;

$tagcount = count($tags);
if ($tagcount > 1) {
for ($i = 1; $i < $tagcount; $i++) { $taglist = $taglist . “, ‘” . $tags[$i]->term_id . “‘”;
}
}

if ($limit) {
$limitclause = “LIMIT $limit”;
} else {
$limitclause = “LIMIT 10”;
}

$q = “SELECT p.ID, p.post_title, p.post_content,p.post_excerpt, p.post_date, p.comment_count, count(t_r.object_id) as cnt FROM $wpdb->term_taxonomy t_t, $wpdb->term_relationships t_r, $wpdb->posts p WHERE t_t.taxonomy =’post_tag’ AND t_t.term_taxonomy_id = t_r.term_taxonomy_id AND t_r.object_id = p.ID AND (t_t.term_id IN ($taglist)) AND p.ID != $post->ID AND p.post_status = ‘publish’ AND p.post_date_gmt < ‘$now’ GROUP BY t_r.object_id ORDER BY cnt DESC, p.post_date_gmt DESC $limitclause;“; $related_posts = $wpdb->get_results($q);

$output = “”;

//不存在相关日志则显示随机日志
if (!$related_posts)
{
if($wp_rp[‘wp_no_rp’] == “text”)
{
$output .= ‘

  • 无相关日志 ‘;
    }
    else

{
if($wp_rp[‘wp_no_rp’] == “random”)
{
$wp_no_rp_text= ‘随机文章:’;
$related_posts = wp_get_random_posts($limitclause);
}

$wp_rp_title = $wp_no_rp_text;
}
}

foreach ($related_posts as $related_post )
{
$output .= ‘

  • ‘;
    if($wp_rp[‘wp_rp_date’])
    {
    $dateformat = get_option(‘date_format’);
    $output .= mysql2date($dateformat, $related_post->post_date) . ” — “; //日期和文章标题间隔符,默认是 —
    }
    $output .= ‘ ‘ . $output . ‘

‘;
$wp_rp_title_tag = $wp_rp[“wp_rp_title_tag”];

if(!$wp_rp_title_tag)
$wp_rp_title_tag =’h3’;
if($wp_rp_title != ”)
$output = ‘<‘.$wp_rp_title_tag.’ >‘.$wp_rp_title .’</‘.$wp_rp_title_tag.‘>‘. $output;
return $output;
}

function wp_related_posts_attach($content)
{
global $wp_rp;
if (is_single()||(is_feed() && $wp_rp[“wp_rp_rss”]))
{
$output = wp_get_related_posts();
$content = $content.$output;
}
return $content;
}
add_filter(‘the_content’, ‘wp_related_posts_attach’,100);