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.
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.
Share Improve this question asked Sep 20, 2020 at 16:15 Shark DengShark Deng 1055 bronze badges1 Answer
Reset to default 1Try 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";
}
?>