2

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();
    } 
?>
4
  • Hi and welcome to WPSE. Could you maybe elaborate a little bit more on what exactly are you trying to do? Some example would be great, I guess. Commented Apr 23, 2019 at 6:15
  • Trying to display related posts by each category that current post is related
    – K H
    Commented Apr 23, 2019 at 6:17
  • OK, but what exactly should it be? Should it show one random post for each category? Or should it show 3 random posts from set of categories? Commented Apr 23, 2019 at 6:19
  • It should show 3 rondom posts from each category
    – K H
    Commented Apr 23, 2019 at 6:20

1 Answer 1

2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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