【发布时间】:2015-05-29 16:06:52
【问题描述】:
我正在学习如何为 Wordpress 创建自定义插件,我正在尝试按类别获取相关帖子。
问题是,我要退回所有帖子,不管它是不是同一类别。
我在 $categoriesIds[] 上做了一个 var_dump,它为每个帖子提取了正确的类别。
我猜 WP_Query 有问题?
有人能指出代码中缺少什么吗?
function Add_related_posts($content) {
// If it's not a singular post, return the content
if (!is_singular('post')) {
return $content;
}
// Get post categories
$categories = get_the_terms(get_the_ID(), 'category');
$categoriesIds = [];
foreach ($categories as $category) {
$categoriesIds[] = $category->term_id;
}
$loop = new WP_Query(array(
'category_in' => $categoriesIds,
'posts_per_page' => 4,
'post_not_in' => array(get_the_ID()),
'orderby' => 'rand'
));
// If there are posts
if ($loop->have_posts()) {
$content .= 'RELATED POSTS:<br><ul>';
while ($loop->have_posts()) {
$loop->the_post();
$content .= '<li><a href="'.get_permalink() .'">' . get_the_title() . '</a></li>';
}
}
$content .= '</ul>';
// Restore data
wp_reset_query();
return $content;
}
【问题讨论】:
标签: wordpress categories posts