T
T
timbird2020-07-06 11:17:22
WordPress
timbird, 2020-07-06 11:17:22

Displaying the category name of a particular product?

Good afternoon!
How to get the name of all categories to which the product belongs?

What I'm doing:
I display the name of the product in the shopping cart, I also want to display clickable names of the categories to which this product belongs, while maintaining the hierarchy.
In this form: category / subcategory, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2020-07-06
@pton

Perhaps this will help you.
I have it organized like
5f03035b33cc4823224711.png
this. To do this, I used a helper function that collects all categories of the current product in a hierarchy. This is necessary to get all the numbers of the top-level parent categories, whether the product is connected directly to the parent category or only to the child category.

function get_unique_deep_term_ids
/**
   * Получает список иерархических линий терминов для указанного или текущего поста в цикле.
   *
   * Возвращается ассоциативный массив вида id => строка id терминов разделенных символом "-" (минус)
   *
   * @param string $taxonomy Название таксономии
   * @param integer/object  [$post_id = 0] ID или объект поста
   *
   * @return array Массив id=>hi_line
   */
  function get_unique_deep_term_ids( $taxonomy, $post_id = 0 ) {
    if ( isset( $post_id->ID ) ) {
      $post_id = $post_id->ID;
    }
    if ( ! $post_id ) {
      $post_id = get_the_ID();
    }

    $terms = get_the_terms( $post_id, $taxonomy );

    if ( ! $terms || is_wp_error( $terms ) ) {
      return array();
    }

    $hierarchies = array();
    foreach ( $terms as $term ) {
      $ancestors = get_ancestors( $term->term_id, 'product_cat' );
      array_unshift( $ancestors, $term->term_id );
      $hierarchies[ $term->term_id ] = implode( '-', array_reverse( $ancestors ) );
    }
    arsort( $hierarchies, SORT_STRING );

    $old = '';
    $hierarchies = array_filter( $hierarchies, function ( $value ) use ( &$old ) {
      $success = false === strpos( $old, $value );
      $old     = $value;

      return $success;
    } );

    return $hierarchies;
  }

Next, we simply collect an array of strings and display it in the right place
/** @var WC_Product $product */
global $product;

$hi_lines = get_unique_deep_term_ids( 'product_cat', $product->get_id() );
foreach ( $hi_lines as $key => $value ) {
  $hi_lines[ $key ] = get_term_parents_list( $key, 'product_cat', $args = array( 'separator' => ' / ' ) );
}

...

// Взято по аналогии из шаблона woocommerce/single-product/meta.php
<?php echo '<div class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . '<br>' . implode('<br>', $hi_lines) . '</div>' ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question