最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp query - How to echo woocommerce category name

programmeradmin1浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

You 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().

发布评论

评论列表(0)

  1. 暂无评论