0

I am using this code to get all posts under the category (name: 'Quizes', slug:'quizes'), which is a customized taxonomy (the slug is st_ai_cat).

// the query
$term_name = get_query_var('taxonomy'); // current taxonomy
$cat_name = get_query_var( 'term' ); // curent cat name
    
    echo $term_name;
    echo $cat_name;
$wp_query = new WP_Query(array('post_type'=>'st_ai',
                               'post_status' => 'publish',
                               'tax_query' => array(
                                   array(
                                      'taxonomy' => $term_name,
                                      'field' => 'slug',
                                      'term' => $cat_name,
                                   )
                               )
                               ));
    
if ( $wp_query->have_posts() ) {
    echo "good";
}
?>

But it always shows nothing. If I remove tax_query, then it can show all posts under the customized taxonomy. But i want to only get posts under the category of Quizes. Why this happens? I checked its usage again.

Thank you.

1

Try to change $cat_name by the category ID.

$term_name = get_query_var('taxonomy'); // current taxonomy
$cate = get_queried_object();
$cat_id = $cate->term_id; // current category ID
    
    echo $term_name;
    echo $cat_id;
$wp_query = new WP_Query(array('post_type'=>'st_ai',
                               'post_status' => 'publish',
                               'tax_query' => array(
                                   array(
                                      'taxonomy' => $term_name,
                                      'field' => 'slug',
                                      'term' => $cat_id,
                                   )
                               )
                               ));
    
if ( $wp_query->have_posts() ) {
    echo "good";
}
?>
4
  • Thanks, it works, just field needs to be 'field' => 'id'.
    – Shark Deng
    Sep 20 '20 at 22:20
  • In my case, $cat_name = get_query_var( 'term' ); should have the 'field' => 'name'. Then it would work. Though I don't know why.
    – Shark Deng
    Sep 20 '20 at 22:21
  • 1
    You are right. Have a good job and a good day
    – Maxime
    Sep 21 '20 at 3:14
  • Thanks! You too.
    – Shark Deng
    Sep 21 '20 at 9:21

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.