在 WooCommerce 中根据属性值显示不同的文本 [英] Display different text based on attribute value in WooCommerce
问题描述
我有一个全局产品属性警告".它有两个值.现在我需要根据产品是否具有属性值 1 或值 2 来显示不同的文本(如果它根本没有该属性,则不应显示任何内容.我可以使用此显示文本
I have a global product attribute 'warning'. It has two values. Now I need to display different text based on if the product has attribute value 1 or value 2 (and if it does not have that attribute at all, nothing should be displayed. I can display text with this
add_action( 'woocommerce_single_product_summary', 'product_warning', 35 );
function product_warning(){
global $product;
$taxonomy = 'pa_warning';
$value = $product->get_attribute( $taxonomy );
if ( $value ) {
$label = get_taxonomy( $taxonomy )->labels->singular_name;
echo '<p>My Text</p>';
}
}
但是如果属性值 1 为真,如何显示文本 1,如果属性值 2 为真,我如何显示文本 2?
but how can I display Text 1 if attribute value 1 is true, and text 2 if attribute value 2 is true?
推荐答案
相反,您将为 pa_warning
使用 2 个术语(值),例如 1
和 2
,为每个相关产品设置正确的术语值.那么你的代码将是:
Instead you will use 2 terms (values) for pa_warning
like 1
and 2
, setting the correct term value for each related product. Then your code will be:
add_action( 'woocommerce_single_product_summary', 'product_warning', 35 );
function product_warning(){
global $product;
$taxonomy = 'pa_warning';
$label_name = wc_attribute_label( $taxonomy );
$term_value = $product->get_attribute( $taxonomy );
if ( $term_value == 1 ) {
echo '<p>' ; __("My text message 1", "woocommerce") . '</p>';
} elseif ( $term_value == 2 ) {
echo '<p>' ; __("My text message 2", "woocommerce") . '</p>';
}
}
代码位于活动子主题(或活动主题)的 function.php 文件中.它应该有效.
Code goes in function.php file of your active child theme (or active theme). It should works.
这篇关于在 WooCommerce 中根据属性值显示不同的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!