代码
functions.php里面添加如下代码
//相关文章
function wp_related_posts($num=6){
global $post;
$data = array();
$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){
$data[] = array(
'id' => $sb->ID,
'post_title' => $sb->post_title,
'post_date' => $sb->post_date,
'link' => get_permalink($sb->ID),
);
$i++;
}
}
if( $i < $num){//自定义文章数不足后通过分类和标签处理
$tagsid = array();
$catid = array();
$thisid[] = $post->ID;
$posttags = get_the_tags();
$catids = get_the_category();
if(!empty($posttags)) {
foreach($posttags as $tag) {
$tagsid[] = $tag->term_id;
}
}
if(!empty($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){
$data[] = array(
'id' => $sb->ID,
'post_title' => $sb->post_title,
'post_date' => $sb->post_date,
'link' => get_permalink($sb->ID),
);
}
}
return $data;
}