Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - Custom product price suffix for selected product categories in WooCommerce

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...