0

I'm learning how to create custom plugins for Wordpress, I am trying to get related posts by category.

The problem is, I am returning all posts regardless of it's category whether it's the same category or not.

I've done a var_dump on the $categoriesIds[] and it is pulling the right category for each post.

I'm guessing something is not right with the WP_Query?

Can someone point out what is missing with the code?

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;
}
0

It needed to be the following: 'category__in' => $categoriesIds, with 2 underscores instead of one.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.