Ulysses
Ulysses

Reputation: 65

How to get the brand name of product in WooCommerce

i need get the brand name of product , i have this code

$product = wc_get_product();

  $type = $product->get_type();      
  $name = (string)$product->get_name();
  $id = (int)$product->get_id(); 
  $sku  = (int)$product->get_sku(); 
  $precio = (int)$product->get_price();

$brand_name = $product->get_brand(); ---> ???

i get this attributes but i don't know how catch the brand name, is there another way ?

enter image description here

Thanks!

Upvotes: 1

Views: 14115

Answers (4)

If you use Woocommerce Brands Plugin:https://docs.woocommerce.com/document/woocommerce-brands/

You can use the next funtion:

echo get_brands();

the plugin includes a function to get the brands, the next lines are declarated in the next plugin file and directory woocommerce-brands/includes/wc-brands-functions/line-64 to 81

function get_brands( $post_id = 0, $sep = ', ', $before = '', $after = '' ) {
    global $post;

    if ( ! $post_id ) {
        $post_id = $post->ID;
    }

    return get_the_term_list( $post_id, 'product_brand', $before, $sep, $after );
}

Upvotes: 2

LoicTheAztec
LoicTheAztec

Reputation: 253901

Is better to use wc_get_post_terms() from a product ID (that allows to get term names instead of WP_Term Objects) and depending on what plugin you are using, the taxonomy will be different:

  • product_brand for Woocommerce Brands plugin
  • yith_product_brand for YITH WooCommerce Brands plugin
  • pa_brand for a custom product attribute

So for example with Woocommerce Brands plugin you will use:

$product_id  = get_the_id();
$product     = wc_get_product( $product_id );

$taxonomy    = `product_brand`;
$brand_names = wp_get_post_terms( $product_id, $taxonomy, array( 'fields' => 'names' ) );

// Get the brand name
$brand_name = reset( $brand_names );

Related:

Upvotes: 11

Ulysses
Ulysses

Reputation: 65

Thanks for the help , I used this code and it works.

$terms = get_the_terms( get_the_ID(), 'product_brand' );

foreach ( $terms as $term ){
    if ( $term->parent == 0 ) {
        $brand_name=  $term->slug;
    }
}  
echo $brand_name;

Upvotes: 2

Jimish Gamit
Jimish Gamit

Reputation: 1024

Use get_the_terms

get_the_terms($product->get_id(),'pa_brand') 

Upvotes: 2

Related Questions