之前大叔引见过 wordpress相干文章完成的要领,例:《代码完成wordpress相干文章》,那末本日说的这个教程,是从优化角度来更合理的完成wordpress相干文章的,至于客观喜好哪一个,本身决议吧!
战略:文章内容相干水平: 手动指定 > 标签 >分类 > 随机
完成体式格局:下面代码直接加到functions.php中即可
function add_related_posts($content){
return $content . wp_related_posts();
}
add_filter ('the_content', 'add_related_posts'); //hook
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',//改成AND则必需是同标签同分类下
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函数
骚年,创作吧。。。。

评论列表