不用插件,自动在WordPress日志尾部显示相关日志

2013-2-26 chenmo 网站建设

以前介绍过通过简码在WordPress插入相关日志(代码在这篇有介绍)或使用插件显示相关日志的方法,各有各的优点。今天的这篇提到的还是相关日志问题:自动在每篇日志的尾部插入相关日志。 

 在你当前主题的 functions.php 文件中添加以下代码即可

//在日志尾部显示相关日志
function wp_get_related_posts()
{
global $wpdb, $post,$table_prefix;
$limit = 8; //显示8篇相关日志
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 . "'";
}
}
$limitclause = "LIMIT $limit";
$q = "SELECT p.ID, p.post_title, 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)
{
$output .= '<li>暂无相关日志。</li>';
}
foreach ($related_posts as $related_post )
{
$dateformat = get_option('date_format');
$output .= '<li>';
$output .= '<a href="'.get_permalink($related_post->ID).'" title="'.wptexturize($related_post->post_title).' ('.mysql2date($dateformat, $related_post->post_date).')">'.wptexturize($related_post->post_title).'</a> ('. $related_post->comment_count .')';
$output .= '</li>';
}
$output = '<h4>你可能还会喜欢的日志:</h4><ul>' . $output . '</ul>';
return $output;
}
function wp_related_posts_attach($content)
{
if (is_single()||is_feed())
{
$output = wp_get_related_posts();
$content = $content . $output;
}
return $content;
}
add_filter('the_content', 'wp_related_posts_attach',100);

 

保存functions.php文件后,紧跟每篇日志的后面都会显示相关的8篇日志。

标签: wordpress 插件 相关日志

Powered by emlog 湘ICP备13007859号 空间由景安网络赞助