WordPress-WooCommerce:为不同产品类别添加差异化价格后缀的代码修正求助
Hey there! Let's get those price suffixes working correctly for your telephone services and signage design products. I spotted a couple of issues in your original code that were preventing it from working as expected—let's break them down and fix things up.
What Was Wrong With the Original Code?
Incorrect
has_termUsage (First Code Snippet)
Thehas_term()function expects the second parameter to be the taxonomy name, not a category slug. For WooCommerce product categories, the taxonomy isproduct_cat, but your code was passingtelephoneandsignagehere, which meant the category check never triggered.Undefined Function (Second Code Snippet)
has_product_categories()isn't a default WooCommerce or WordPress function—you'd need to define it separately, which adds unnecessary complexity. Sticking with the nativehas_term()is more reliable.
Corrected Code
This snippet will properly check product categories, handle variable products, and add the right suffix:
add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 20, 2 ); function conditional_price_suffix( $price, $product ) { // Get the correct product ID (handle variations by using parent product ID) $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id(); // Check if product belongs to the "telephone" category if( has_term( 'telephone', 'product_cat', $product_id ) ) { $price .= ' ' . __('per month', 'woocommerce'); } // Check if product belongs to the "signage" category elseif( has_term( 'signage', 'product_cat', $product_id ) ) { $price .= ' ' . __('per hour', 'woocommerce'); } return $price; }
Key Improvements
- Proper Taxonomy Reference: Uses
product_cat(WooCommerce's default product category taxonomy) inhas_term(). - Variable Product Support: Checks the parent product's category for variations, since variations inherit categories from their parent.
- Translation Ready: Includes the
woocommercetext domain so the suffixes can be translated if needed. - Clean Conditionals: Uses
elseifto avoid adding both suffixes if a product accidentally ends up in both categories.
How to Use This
- Verify Category Slugs: Make sure your product categories have the slugs
telephoneandsignage(check this in WordPress Admin → Products → Categories, edit a category and look at the slug field). - Add the Code: Paste this snippet into your child theme's
functions.phpfile, or use a code snippet plugin like Code Snippets (safer than editing theme files directly if you're not comfortable). - Clear Cache: Flush your WooCommerce cache and browser cache to see the changes take effect.
内容的提问来源于stack exchange,提问作者Dan Nolan

