Brands plugin switchover issue with custom code in WooCommerce

As part of my WooCommerce store, we were using a plugin to facilitate product brands. We originally had a third-party one called YITH Brands. It worked for a while, but it doesn't integrate well with others, so we switched over to the official WC Brands. The problem is, our previous web developers coded some functionality from YITH into our website, and so disabling this plugin breaks everything. It appears to be the code that displays the brand name above the product title, as below: add_action( 'woocommerce_before_shop_loop_item_title', 'aq_display_brand_before_title' ); function aq_display_brand_before_title(){ global $product; $product_id = $product->get_id(); $brands = wp_get_post_terms( $product_id, 'yith_product_brand' ); foreach( $brands as $brand ) echo '<a href="'.get_term_link($brand->term_id).'">'.$brand->name.'</a>'; I've found some similar code in the documentation for WC Brands, but using it doesn't display on the website. add_action( 'woocommerce_single_product_summary', 'wc_brands_add_brand_name', 1 ); function wc_brands_add_brand_name() { global $product; $brands = implode(', ', wp_get_post_terms($product->get_id(), 'product_brand', ['fields' => 'names'])); echo "<p>Brand: " . $brands . "</p>"; Is there a way I can alter the first piece of code so that it pulls the variables and such from WC Brands? That way, we keep the functionality and I can safely disable YITH.

Comment (1)

Jese Leos

September 12, 2024

Verified user

For official WooCommerce Brands plugin, the taxonomy is "product_brand" instead of "yith_product_brand". With your previous developer code that you provided, there are some missing things to avoid this kind of issue. Also, it is better to use get_the_terms() as results are cached, avoiding a database query each time the page is displayed. Replace the code with: add_action( 'woocommerce_before_shop_loop_item_title', 'aq_display_brand_before_title' ); function aq_display_brand_before_title(){ global $product; $taxonomy = 'product_brand'; // <= Here we set the correct taxonomy $brand_terms = get_the_terms( $product->get_id(), $taxonomy ); // Check if it's the correct taxonomy and if there are terms assigned to the product if ( $brand_terms && ! is_wp_error( $brand_terms ) ) { // Loop through assigned terms foreach( $brand_terms as $term ) { if ( is_a($term, 'WP_Term') ) { echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>'; } } } } It should work without issue, in a lighter way.

You’ll be in good company