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

chen'mo
2013-02-26 / 0 评论 / 1,167 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于1970年01月01日,已超过19851天没有更新,若内容或图片失效,请留言反馈。

以前介绍过通过简码在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篇日志。

0
Emlog全部调用所有的标签页面源码
« 上一篇 02-25
WordPress 简易信息统计(代码)
下一篇 » 02-26

评论 (0)

插入图片