之前大叔介紹過(guò) WordPress相關(guān)文章實(shí)現(xiàn)的方法,例:《代碼實(shí)現(xiàn)WordPress相關(guān)文章》,那么今天說(shuō)的這個(gè)教程,是從優(yōu)化角度來(lái)更合理的實(shí)現(xiàn)WordPress相關(guān)文章的,至于客觀喜歡哪個(gè),自己決定吧!
策略:文章內(nèi)容相關(guān)程度: 手動(dòng)指定 > 標(biāo)簽 >分類 > 隨機(jī)

實(shí)現(xiàn)方式:下面代碼直接加到functions.php中即可
- function?add_related_posts($content){
- return?$content?.?wp_related_posts();
- }
- function?wp_related_posts(){
- global?$post;
- ????$num?=?5;
- $counter?=?1;
- ????$exclude_id?=?get_post_meta($post->ID,’related’,true);
- if?($exclude_id){
- ????????$args?=?array(
- ????????????‘post_type’?=>?array(‘post’),
explode(‘,’,?$exclude_id),
- ????????????‘posts_per_page’?=>?$num
- ????????$posts?=?get_posts($args);
- foreach($posts?as?$sb){
- ????????????$output?.=?‘<li><a?href=“‘?.?get_permalink($sb->ID)?.?‘”>’?.?$sb->post_title?.?‘</a></li>’;
- $i++;
- ????????}
- ????if(?$i?<?$num){
- $tagsid?=?array();
- ????????$catid?=?array();
- $thisid[]?=?$post->ID;
- ????????$posttags?=?get_the_tags();
- $catids?=?get_the_category();
- ????????if(!emptyempty($posttags))?{
- foreach($posttags?as?$tag)?{
- ????????????????$tagsid[]?=?$tag->term_id;
- ????????}
- if(!emptyempty($catids))?{
- ????????????foreach($catids?as?$cat)?{
- $catid[]?=?$cat->term_id;
- ????????????}
- ????????$args?=?array(
- ????????????‘post__not_in’?=>?$thisid,
- ????????????‘posts_per_page’?=>?($num?–?$i),
array(
- ????????????????‘relation’?=>?‘OR’,
- array(
- ????????????????????‘taxonomy’?=>?‘post_tag’,
- ????????????????????‘terms’????=>?$tagsid,
- ????????????????array(
- ????????????????????‘field’????=>?‘term_id’,
$catid,
- ????????????????),
- ????????);
- $rsp?=?get_posts($args?);
- ????????foreach($rsp?as?$sb){
- $output?.=?‘<li><a?href=“‘?.?get_permalink($sb->ID)?.?‘”>’?.?$sb->post_title?.?‘</a></li>’;
- ????????????$i++;
- ????}
- $final?=?‘<h3>相關(guān)文章</h3><ul>’?.?$output?.?‘</ul>’;
- ????return?$final;
-

如想自定位置,并調(diào)整樣式,則去掉the_content
的鉤子,然后手動(dòng)調(diào)用wp_related_posts
函數(shù)
騷年,創(chuàng)作吧。。。。