Home > OS >  How to get the category
How to get the category

Time:07-29

There is a cycle that outputs products

<?php
$args = array('post_type' =>
'product');
$loop = new WP_Query($args);
foreach ($loop->posts as $have_post) : ?>
  <div >
    <a href="
                  <?php
                  $permalink = get_post_permalink($have_post->ID);
                  echo $permalink;
                  ?>
                  " >
      <div >
        <?php
        echo $have_post->name; ?>
      </div>
      <div >
        <?php
        echo get_the_post_thumbnail($have_post->ID, 'full', array('alt' => $have_post->post_title, 'data-product_id' => $have_post->ID)); ?>
      </div>
      <div ><?php echo $have_post->post_title; ?></div>
      <div >
        <?php
        $price = get_post_meta($have_post->ID, '_price', true);
        echo $price; ?> руб.
      </div>
    </a>
  </div>
<?php endforeach; ?>

Need to show the category of current product here. I cant get the category. Please help

<div ><?php echo $have_post->name; ?></div>

CodePudding user response:

You could use get_the_terms to get the correct terms. I believe it's product_cat the correct taxonomy.

$terms = get_the_terms( $have_post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    $product_cat_name = get_cat_name($product_cat_id); 
    break;
}

CodePudding user response:

Try get_the_category( $post->ID );

  • Related