I have a WP_Query that outputs featured products. For each product I would also like to link to the category of that product, but I’m not sure how.
I think this is close to being my answer, but I’m not sure how to put it all together. How to get category link without a database query
My query so far is:
<?php
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN'
),
),
'posts_per_page' => 8
);
$loop = new WP_Query( $args ); ?>
<ul class="product-list">
<?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li class="product-list__item">
<a href="https://wordpress.stackexchange.com/questions/274473/<?php echo get_permalink( $loop->post->ID ) ?>"
<?php the_title(); ?>
</a>
Link to the product category here!
Any help is much appreciated.
1 Answer
You can use get_the_term_list()
to output a comma-separated list of links to product categories:
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li class="product-list__item">
<a href="https://wordpress.stackexchange.com/questions/274473/<?php the_permalink() ?>">
<?php the_title(); ?>
</a>
<?php echo get_the_term_list( get_the_ID(), 'product_cat', '', ', ' ); ?>
</li>
<?php endwhile; ?>
Note that when you’re inside ‘the loop’ (i.e. between $loop->the_post();
and endwhile
) you don’t need to pass an ID to get_permalink()
, you can just use the_permalink()
.
Also, in your code you’re missing the last >
from the opening anchor tag, make sure to fix that.