How to display recent / random posts by its category

trying to display random posts from each category that my custom post belongs to (it is related to 2 categories). I am trying to get post categories by id.
I have tried to put category ID manually but still it display random posts from ALL posts in his type.
Can anyone help me with this?

<?php
    $term_list = wp_get_post_terms( $post->ID, 'listing-category', array( 'fields' => 'ids' ) );
    $args = array(
        'post_type' => 'listing',
        'category' => $term_list[0],
        'post_status' => 'publish',
        'orderby'   => 'rand',
        'posts_per_page' => 3,
        );

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $rand_posts .= '<li> <a href="'. get_the_permalink() .'">'. get_the_title() .'</a> </li>';
        }
        echo $rand_posts;
        wp_reset_postdata();
    } 
?>

1 Answer
1

OK, so if you want to show 3 random posts from every category that current post is assigned to, then…

First of all you should loop through all terms and get random posts for every term:

$term_list = wp_get_post_terms( $post->ID, 'listing-category', array( 'fields' => 'ids' ) );
if ( $term_list && ! is_wp_error($term_list) ) {
    foreach ( $term_list as $term_id ) {
        // get random posts for given term
    }
}

And currently you get random posts from every category, because there is one minor flaw with your query:

$args = array(
    'post_type' => 'listing',
    'category' => $term_list[0], // <- this works with built-in post categories, not your custom taxonomy called listing-category
    'post_status' => 'publish',
    'orderby'   => 'rand',
    'posts_per_page' => 3,
);

So you should use Tax_Query:

$args = array(
    'post_type' => 'listing',
    'post_status' => 'publish',
    'orderby' => 'rand',
    'posts_per_page' => 3,
    'tax_query' => array(
        array( 'taxonomy' => 'listing-category', 'field' => 'term_id', 'terms' => <TERM_ID> ), // change <TERM_ID> for real term
        // so in your code it's $term_list[0] and in my loop just $term_id
    )
);

Leave a Comment