WooCommerce:有条件地隐藏产品属性

WooCommerce: Conditionally hide product attributes

我显示了所有产品属性的列表。在我的例子中是颜色。 例如,产品的颜色可以是 bluelight blue。 这些用于存档页面上的过滤目的。

但在产品页面上我只想显示其中一个(浅蓝色)。 如果我们存在另一个属性,是否有任何方法可以排除一个属性。

这可能是手动方式,因为只有 5-10 个。

目前我正在使用以下代码来显示属性:

global $product;
$pa_colors = wc_get_product_terms( $product->get_id(), 'pa_color', array( 'fields' =>  'all', 'orderby' => 'menu_order' ) );

if( $pa_colors ) :

    foreach ( $pa_colors as $pa_color ) :
        echo $pa_color->name;
    endforeach;
    
endif; 

有几种方法可以做到这一点

使用了 php 个函数


当在 array 中找到 $pa_color->name 时,我们将其替换为数组中的第一项。如果不是,则满足 else 条件。 因为这样会出现重复值,所以对数组进行重复值过滤

global $product;

if ( is_a( $product, 'WC_Product' ) ) {
    $pa_colors = wc_get_product_terms( $product->get_id(), 'pa_color', array( 'fields' =>  'all', 'orderby' => 'menu_order' ) );

    if( $pa_colors ) {
        // Set colors, if a color is found in the array, the first item in the array will be displayed
        $colors = array( 'light blue', 'blue', 'dark blue', 'moonstone blue' );
        
        // Loop
        foreach ( $pa_colors as $pa_color ) {
            // in_array — Checks if a value exists in an array
            if ( in_array ( $pa_color->name, $colors ) ) {
                $output[] = $colors[0];
            } else {
                $output[] = $pa_color->name;
            }
        }
        
        // Removes duplicate values from an array
        $result = array_unique( $output );

        // Result
        echo '<pre>', print_r( $result, 1 ), '</pre>';
    }
}