我正在学习如何为Wordpress创建自定义插件,我正在尝试按类别获取相关帖子。
问题是,我将返回所有帖子,无论其类别是否相同。
我已经对$CategoriesID[]进行了var\\u转储,它正在为每个帖子提取正确的类别。
我猜WP\\u查询有问题?
有人能指出代码中缺少了什么吗?
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;
}