Reputation: 126
I'm running the next code:
Determining category id for category page
<?php
$cat_id = get_queried_object_id();
echo 'cat_id = ' . $cat_id;?>
Trying to get this category products:
$args = array(
'post_type' => 'product',
'posts_per_page' => 12,
'cat' => $cat_id
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<div class="product <?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
<?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' ); ?>
<?php if($featured_image) { ?>
<div class="product-image" style="background-image: url('<?php echo $featured_image[0]; ?>')">
<a href="<?php echo $product->get_permalink();?>"></a>
</div>
<?php } ?>
<a href="<?php echo $product->get_permalink();?>"><?php the_title(); ?></a>
<p><? echo $product->term_id; ?></p>
<?php if ($average = $product->get_average_rating()) : ?>
<?php echo '<div class="star-rating" title="'.sprintf(__( 'Рейтинг %s из 5', 'woocommerce' ), $average).'"><span style="width:'.( ( $average / 5 ) * 100 ) . '%"><strong itemprop="ratingValue" class="rating">'.$average.'</strong> '.__( 'из 5', 'woocommerce' ).'</span></div>'; ?>
<?php endif; ?>
<span class="price"><?php echo $product->get_price_html(); ?></span>
<?php
global $wp_query;
$terms_post = get_the_terms( $post->cat_ID , 'product_cat' );
foreach ($terms_post as $term_cat) {
$term_cat_id = $term_cat->term_id;
echo 'My category id: ' . $term_cat_id;
}
?>
</div>
<?php endwhile; ?>
And this displays nothing. I've checked the categories of products while getting all categories. cat_id = 15, product_cat_id = 15, but the output is clear:
Upvotes: 0
Views: 285
Reputation: 126
To get products of the category (on a category page)
$cat_id = get_queried_object_id();
$term = get_term( $cat_id, 'product_cat' );
$slug = $term->slug;
$args = array(
'post_type' => 'product',
'posts_per_page' => 12,
'product_cat' => $slug
);
Upvotes: 0
Reputation: 91
They say here
That you can use get_term_by()
$id = 42;
if( $term = get_term_by( 'id', $id, 'product_cat' ) ){
echo $term->name;
}
Upvotes: 1