根据WooCommerce中的属性值显示不同的文本

问题描述

我有一个全局产品属性“警告”。它有两个值。现在,我需要根据产品的属性值为1还是2显示不同的文本(如果根本没有该属性,则什么也不显示。我可以使用此显示文本

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为true,如何显示文本1,如果属性值2为true,如何显示文本2?

解决方法

相反,您将为pa_warning使用2个术语(值),例如12,为每个相关产品设置正确的术语值。然后您的代码将是:

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文件。应该可以。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...