Freddy
Freddy

Reputation: 857

WordPress: Get and display posts which have the same term

I have a custom taxonomy called type. Type has the following options:

When on a post, I want to showcase posts which have the same type. I.e. if you're on a case study, I want it to display other case studies.

The maximum related posts I want to show is two, but if there is only one post that has that tag, then I only want it to display one.

Not sure where my query is falling apart:

global $post;

$blog_type = get_terms('type');

$args = array(
    'post_type' => 'resources',
    'category__in'   => wp_get_post_categories($post->ID ),
    'posts_per_page' => 2,
    'post__not_in'   => array($post->ID ),
    'terms' => $blog_type,
);

$relatedPosts = new WP_Query( $args );

Upvotes: 0

Views: 929

Answers (1)

Jainil
Jainil

Reputation: 1496

You need to use tax_query here:

$term_list = wp_get_post_terms( $post->ID, 'type', array( 'fields' => 'ids' ) );
$args = array(
    'post_type' => 'resources',
    'posts_per_page' => 2,
    'post__not_in' => array( $post->ID ),
    'tax_query' => array(
        array(
            'taxonomy' => 'type',
            'field' => 'term_id',
            'terms' => $term_list
        )
    )
);

$relatedPosts = new WP_Query( $args );

Upvotes: 1

Related Questions