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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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";
}
?>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0