之前大叔介紹過 wordpress相關文章實現的方法,例:《代碼實現WordPress相關文章》,那么今天說的這個教程,是從優化角度來更合理的實現wordpress相關文章的,至于客觀喜歡哪個,自己決定吧!
策略:文章內容相關程度: 手動指定 > 標簽 >分類 > 隨機

實現方式:下面代碼直接加到functions.php中即可
- function?add_related_posts($content){
- ????return?$content?.?wp_related_posts();
- }
- add_filter?('the_content',?'add_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_status'?=>?'publish',
- ????????????'post_type'?=>?array('post'),
- ????????????'post__in'?=>?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_type'?=>?'post',
- ????????????'post__not_in'?=>?$thisid,
- ????????????'ignore_sticky_posts'?=>?1,
- ????????????'posts_per_page'?=>?($num?-?$i),
- ????????????'tax_query'?=>?array(
- ????????????????'relation'?=>?'OR',
- ????????????????array(
- ????????????????????'taxonomy'?=>?'post_tag',
- ????????????????????'field'????=>?'term_id',
- ????????????????????'terms'????=>?$tagsid,
- ????????????????),
- ????????????????array(
- ????????????????????'taxonomy'?=>?'category',
- ????????????????????'field'????=>?'term_id',
- ????????????????????'terms'????=>?$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>相關文章</h3><ul>'?.?$output?.?'</ul>';
- ????return?$final;
- }
調用方法
如需加入自定義相關文章,只需新建自定義欄目,加入文章id即可,多篇文章用,隔開

如想自定位置,并調整樣式,則去掉the_content
的鉤子,然后手動調用wp_related_posts
函數
騷年,創作吧。。。。
可以可以,很實用的,,
2015-07-13 上午 10:15騷年,創作吧
2015-06-15 上午 10:29