Custom product price suffix for selected product categories in Woocommerce

190
June 21, 2018, at 09:30 AM

I would like to display a piece of text after the price tag in WooCommerce. I have a code that is working for my functions.php, but it shows on all product categories.

I was wondering if someone knows how to make this custom text to show for only selected categories; or even better, unselected product categories as there are a lot more product categories that will display the text than the ones who doesn't.

My actual code:

add_filter( 'woocommerce_get_price_html', 'custom_price_message' );
function custom_price_message( $price ) {
    $mt = ' per M/T';
    return $price . $mt;
}

Any help on this please.

Answer 1

Try the following code that uses has_term() conditional function for defined product categories:

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 );
function conditional_price_suffix( $price, $product ) {
    // HERE define your product categories (can be IDs, slugs or names)
    $product_categories = array('t-shirts','hoodies');
    if( has_term( $product_categories, 'product_cat', $product->get_id() ) )
        $price .= ' ' . __('per M/T');
    return $price;
}

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

To exclude defined product categories you will replace:

if( has_term( $product_categories, 'product_cat', $product->get_id() ) )

simply by:

if( ! has_term( $product_categories, 'product_cat', $product->get_id() ) )
Rent Charter Buses Company
READ ALSO
Why is my Docker Symfony project with Composer consuming so much memory?

Why is my Docker Symfony project with Composer consuming so much memory?

I'm deploying my symfony project in prodIt works fine when I simply run docker-compose up

188
i not know how sum amount decimal number using php

i not know how sum amount decimal number using php

I sum some amount using php but i try this codefor example

117
Change individual mini cart widget quantity WooCommerce

Change individual mini cart widget quantity WooCommerce

I am using WooCommerce mini cart widget and I trying to enable the user to add or remove items from the cart on an individual basis via AJAXIt is currently only possible by removing all quantities of the same product

197
Hook to update post date to current date

Hook to update post date to current date

I want to update the post date of posts older than 21 days to the current dateI'm looking for a hook to achieve this goal

151