Skip to main content

WooCommerce has a great plugin for categorizing your products at the brand level called WooCommerce Brands.  It helps you group your products by their brand and assigns the correct schema data used by Google for E-Commerce stores.

WooCommerce Brands has great documentation when it comes to shortcodes, but not a lot of information on how to actually query the brand data at a code level.  I needed to grab the brand name on a page template to then apply other logic based on the product brand.  It’s pretty simple to do using the WordPress function wp_get_post_terms.

Below is an example of how to accomplish this by passing the 3 variables the wp_get_post_terms function needs:

$product->id = The ID of the product

product_brand = the term to query

array(“fields” => “all”) = I want to get all of the fields associated with the product_brand term.

$productBrandAtt = wp_get_post_terms( $product->id, 'product_brand', array("fields" => "all") );

This function returns an array like so:

array(1) {
  object(WP_Term)#2389 (10) {
    string(7) "Apple"
    string(7) "apple"
    string(13) "product_brand"
    string(136) "Discover the innovative world of Apple and shop everything iPhone, iPad, Apple Watch, Mac, and Apple TV, plus explore accessories, entertainment, and expert device support."
    string(3) "raw"

In this array we a few items you may want to use such as

term_id = the unique term id
name = brand name
slug = slug of the brand
term_group = if grouped the group name
description = description of brand if set
parent = parent id if any
count = total count of products using this term

Now for my page template I only needed the brand name so to accomplish this I just grab it from the array.  Due to the query only returning the brand term for that product I know there will be no more than one result as my products are only associated to a single brand.  If you have multiple brands for a single product you would need a foreach loop to grab all of the data you need and format appropriately.  But like I mentioned my products only have a single brand assigned so here’s the full code snippet to grab the brand and output only the name to my PHP variable.

$productBrandTerm = wp_get_post_terms( $product->id, 'product_brand', array("fields" => "all") );
$productBrandName = $productBrandTerm[0]->name;

Leave a Reply