Search code examples
wordpresscategoriesposts

Wordpress - Custom plugin to return related posts by category


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

Solution

  • Categories are pulled as expected. But in argument in WP_Query, you got one problem. It should be category__in, NOT category_in.

    Try this:

    'category__in'    => $categoriesIds,
    

    See documentation: http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters