Athon
Athon

Reputation: 130

Replace dynamically custom tags in Woocommerce product short description

For a Woocommerce webshop I am using WooCommerce Brands plugin and I'm trying to replace dynamically specific custom tags in the product short description by specific product values as:

For example, The tags to be replaced could be something like:

Also, it be great for replaced product category and product brand to have the link to the product category or product brand archive pages.

I'm not sure where to look for. I've searched all over google but I can't find anything related and useful unfortunately.

Any help is appreciated.

Upvotes: 3

Views: 1261

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254211

Update 2

Here is the way to do it using this custom function hooked in woocommerce_short_description filter hook, that will replace specific custom tags by product data values in single product pages short description.

Now as product can have many product categories and many product brands, I keep only the first one.

The code:

add_filter('woocommerce_short_description', 'customizing_wc_short_description', 20, 1);
function customizing_wc_short_description($short_description){
    if( is_archive() ) return $short_description;
    global $product, $post;

    // 1. Product categories (a product can have many)
    $catgories = array();
    foreach( wp_get_post_terms( $post->ID, 'product_cat' ) as $term ){
        $term_link   = get_term_link( $term, 'product_cat' );
        $catgories[] = '<a class="cat-term" href="'.$term_link.'">'.$term->name.'</a>'; // Formated
    }

    // 2. Product brands (a product can have many)
    $brands = array();
    foreach( wp_get_post_terms( $post->ID, 'product_brand' ) as $term ){
        $term_link   = get_term_link( $term, 'product_brand' );
        $brands[] = '<a class="brand-term" href="'.$term_link.'">'.$term->name.'</a>'; // Formated
    }

    // 3. The data array of tags to be replaced by product values
    $data = array(
        '%product_name%'  => $product->get_name(),
        '%category_name%' => reset($catgories), // We take the first product category
        '%brand_name%'    => reset($brands),
    );

    $keys   = array_keys($data); // The Tags
    $values = array_values($data); // The replacement values

    // Replacing custom tags and returning "clean" short description
    return str_replace( $keys, $values, $short_description);
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 1

Related Questions