我正在尝试在每个帖子页面的内容下按类别自动显示一些相关帖子。
// Related Posts by Category
function example_cats_related_post() {
$post_id = get_the_ID();
$cat_ids = array();
$categories = get_the_category( $post_id );
if(!empty($categories) && !is_wp_error($categories)):
foreach ($categories as $category):
array_push($cat_ids, $category->term_id);
endforeach;
endif;
$current_post_type = get_post_type($post_id);
$query_args = array(
'category__in' => $cat_ids,
'post_type' => $current_post_type,
'post__not_in' => array($post_id),
'posts_per_page' => '4',
);
$related_cats_post = new WP_Query( $query_args );
if($related_cats_post->have_posts()):
while($related_cats_post->have_posts()): $related_cats_post->the_post();
return '<ul>
<li>
<a href="'.get_permalink().'">'.get_the_post_thumbnail($post->ID, array(150, 100)).get_the_title().'</a>
</li>
</ul>';
endwhile;
// Restore Original Post Data
wp_reset_postdata();
endif;
}
然后我成功将其添加到帖子内容后面:
// Add After Content
function related_posts_after($content) {
if ( is_single() ) {
ob_start();
$aftercontent = example_cats_related_post();
$fullcontent = $content.$aftercontent;
return $fullcontent;
} else {
return $content;
}
}
add_filter('the_content', 'related_posts_after');
问题是只显示一篇相关帖子,而不是参数中的数字(posts_per_page)。我尝试了不同的修改但没有结果。预先感谢您!
问题出在你的时间上。
您不能在那里使用返回,因为返回出口。需要 echo 或关闭/打开 PHP。
return '<ul>
<li>
<a href="'.get_permalink().'">'.get_the_post_thumbnail($post->ID, array(150, 100)).get_the_title().'</a>
</li>
</ul>';