WordPress的强大和易用,在于无数的主题和插件,但插件多了会影响网站的速度和安全。如果能用简单代码实现需要的功能,还是用代码好了。
在每篇文章的末尾,显示相关文章,可以更好的留住客户。
下面提供两种方法:
第一种
在所用主题的functions.php文件中,添加如下代码
function wp_get_related_posts()
{
global $wpdb, $post,$table_prefix;
$limit = 10; //How Many Related Posts Displayed
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 .= ‘No Related Posts ’;
}
foreach ($related_posts as $related_post )
{
$dateformat = get_option(‘date_format’);
$output .= ‘’; ’;
$output .= ‘ID).'” title=”‘.wptexturize($related_post->post_title).’ (‘.mysql2date($dateformat, $related_post->post_date).’)”>’.wptexturize($related_post->post_title).' (‘.$related_post->comment_count .’)’;
$output .= ‘
}
$output = ‘Related Posts
’ . $output . ‘
’;
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);
第二种
在所用主题的single.php添加,一般添加在之后
Related Posts
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[0]->term_id;
$args=array(
’tag__in’ => array($first_tag),
’post__not_in’ => array($post->ID),
’showposts’=>10,//Display 10 related posts
’caller_get_posts’=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>- ” rel=”bookmark” title=””>
endwhile;
}
}
wp_reset_query();
?>
文章名称:《WordPress两种不需要插件添加相关文章的方法》
文章链接:https://www.liuzhanwu.com/10698.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
相关推荐
ZJI:香港葵湾E型服务器,Intel Gold 6138/32GB内存/1TB SSD/30Mbps,640元/月
#黑五#Zalvis:主机托管七折优惠,vps主机8折优惠,$ 39.95 /月起,可选美国/德国/芬兰机房
#618大促#最后一天|凌霞软件旗下强大易用的建站工具 Halo:永久授权 660元起,10台6000元,即买即赠SSL证书
#6.18促销#Themebetter:WordPress主题特惠7折,DUX主题折后559元,不限制域名授权数目
ZJI: 香港云地新上十核心机型,6折,Intel E5-2680v2/32GB ECC/1TB SSD/30Mbps BGP@不限流量,540元/月
#20周年庆典#SiteGround:稳定博客/外贸主机,免费站点转移/电子邮件/SSL证书/CDN和备份服务等,月付$2.99/年付35.88美元起
#新春特惠#莱卡云:韩国/香港/美国云服务器首月仅需9.9元,不限制新老用户,4C4G的年付249元/起,独服450.00元/月起
#圣诞节促销#Hostarmada:共享主机80%优惠,低至$1.99/月起,vps和经销商主机50%优惠,$19.6/月起,可选新加坡/法兰克福等9个机房