Tried at least 5 SO answers, but nothing is working for me. I have this code and I want to output all the products within the category together with the category name on top:
<?php $params = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug', //This is optional, as it defaults to 'term_id'
'terms' => array('bronchoscopes'),
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
),
)
);
$products = new WP_Query($params);
?>
<?php if ($products->have_posts()) : // (3) ?>
<?php while ($products->have_posts()) : // (4)
$products->the_post(); // (4.1) ?>
<?php the_title(); // (4.2) ?>
<?php echo single_term_title(); ?>
<?php echo the_category(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); // (5) ?>
<?php else: ?>
<p>
<?php _e( 'No Products' ); // (6) ?>
</p>
<?php endif; ?>
But I'm getting only my two products on the page, not the category name itself. What's the deal?
Tried at least 5 SO answers, but nothing is working for me. I have this code and I want to output all the products within the category together with the category name on top:
<?php $params = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug', //This is optional, as it defaults to 'term_id'
'terms' => array('bronchoscopes'),
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
),
)
);
$products = new WP_Query($params);
?>
<?php if ($products->have_posts()) : // (3) ?>
<?php while ($products->have_posts()) : // (4)
$products->the_post(); // (4.1) ?>
<?php the_title(); // (4.2) ?>
<?php echo single_term_title(); ?>
<?php echo the_category(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); // (5) ?>
<?php else: ?>
<p>
<?php _e( 'No Products' ); // (6) ?>
</p>
<?php endif; ?>
But I'm getting only my two products on the page, not the category name itself. What's the deal?
Share Improve this question asked Feb 9, 2018 at 15:04 LimpulsLimpuls 3071 gold badge3 silver badges16 bronze badges1 Answer
Reset to default 1You create WP_Query
with tax_query
and retrieve posts with category slug bronchoscopes
. If you hardcoded category slug - you can hardcode also category name. Use get_the_terms() inside loop and you will retrieve all categories attached to post. Or get_the_term_list().