Wordpress - 按类别 return 相关帖子的自定义插件

Wordpress - Custom plugin to return related posts by category

我正在学习如何为 Wordpress 创建自定义插件,我正在尝试按类别获取相关 posts。

问题是,我将返回所有 post,无论其类别是否相同。

我在 $categoriesIds[] 上做了一个 var_dump,它为每个 post 提取了正确的类别。

我猜 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;
}

类别已按预期提取。但是在 WP_Query 的争论中,你遇到了一个问题。 它应该是 category__in,而不是 category_in

试试这个:

'category__in'    => $categoriesIds,

查看文档:http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters