Brad Fletcher
Brad Fletcher

Reputation: 3593

Display child product category from specific parent in WooCommerce loop product title

I have the brands setup in WooCommerce's Category as you can see in the picture.

I want to output the term for this category into the title of the product with a link, linking to all discs from that brand.

I have created this function but its showing ALL the brands to all products, not just the assigned brand.

add_action( 'woocommerce_shop_loop_item_title', 'get_brand', 10 );

function get_brand() {

  $terms = get_terms(
      array(
          'taxonomy'   => 'product_cat',
          'hide_empty' => false,
          'child_of'   => 32
      )
  );

  // Check if any term exists
  if ( ! empty( $terms ) && is_array( $terms ) ) {
      // Run a loop and print them all
      foreach ( $terms as $term ) { ?>
          <a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
              <?php echo $term->name; ?>
          </a><?php
      }
  }

}

Backend

Upvotes: 1

Views: 1182

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253887

To get product category terms set for a product (defining some arguments), you need to use instead wp_get_post_terms() function with the right parent term argument for "brand" as follows:

add_action( 'woocommerce_shop_loop_item_title', 'display_loop_brand', 10 );
function display_loop_brand() {
    $taxonomy = 'product_cat';

    // Get the "brand" child term set for the product
    $brand_terms = (array) wp_get_post_terms( get_the_id(), $taxonomy, array(
        'hide_empty' => false,
        'parent'     => 32 // <= Here set the "brand" term id
    ) );

    if ( ! empty( $brand_terms ) ) {
        // Loop through terms array
        foreach ( $brand_terms as $term ) {
            $link = get_term_link( $term, $taxonomy ); // Get the term link

            echo'<a href="' . esc_url( $link ) . '">' . $term->name . '</a>';
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Upvotes: 3

Related Questions