1

In single.php :

I want to get all posts with at least one category in common with the current post.

I tried reading through the wordpress codex documentation but I found it rather confusing (I'm new to php & wordpress!). I've already used php on wordpress but when it comes to getting posts using filters it's still not clear to me how to do it.

I've written the following bit of code/pseudocode to explain the bit of code I'm looking for.

<?php 

$current_post_categories = get_the_category();

$related_posts_array = get_posts( *that have at least one category that exists in $current_post_categories* );

?>

Any help or at least a good link with a nice tutorial/explanation about getting posts using filters would be much appreciated.

Thank you in advance!

4

You can use the category__in argument:

// use get_the_category( $post_id ) if you are outside the loop
$categories = get_the_category();

if( $categories ){

    $related_posts = get_posts( array( 'category__in' => $categories ) );

}

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.