Custom product price suffix for selected product c

2019-02-26 03:45发布

问题:

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.

回答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() ) )