How can I alter this code in my Wordpress functions.php as part of a plugin switchover?

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.

To adjust your code to work with WooCommerce Brands instead of YITH Brands, you’ll need to replace the references to 'yith_product_brand' with 'product_brand', which is used by WC Brands.

Here’s how you can modify the original code to work with WooCommerce Brands:

php

Copy code

add_action( 'woocommerce_before_shop_loop_item_title', 'aq_display_wc_brand_before_title' );
function aq_display_wc_brand_before_title(){
    global $product;
    $product_id = $product->get_id();
    // Fetch the brands using WC Brands taxonomy
    $brands = wp_get_post_terms( $product_id, 'product_brand' );
    
    // Display each brand as a link
    if ( !empty( $brands ) && !is_wp_error( $brands ) ) {
        foreach( $brands as $brand ) {
            echo '<a href="'.get_term_link( $brand->term_id ).'">'.$brand->name.'</a>';
        }
    }
}

Key changes:

  1. Changed 'yith_product_brand' to 'product_brand', which is the taxonomy WC Brands uses.
  2. Added a check to ensure that $brands is not empty and not an error.

This should replicate the YITH Brands functionality using WC Brands without breaking your website. Once you’re sure this works, you can safely disable the YITH Brands plugin.