首页 > 解决方案 > 根据特定元素值隐藏元素

问题描述

我有一家 woocommerce 商店,我正在导入自定义字段,例如“颜色”、“长度”等(大约 10 个字段),但并非所有产品都具有这些字段的值。有没有办法隐藏整个元素的值为空或空。在前端,元素显示如下: 长度:10 厘米 高度:20 厘米 所以基本上如果没有特定产品的长度,我想隐藏它。

链接查看:(查看产品额外详细信息。在此示例中,我只想显示直径并隐藏其余部分,因为它们是空的)

https://qadeemarabia.com/product/3d-bird-cookie-jar-off-white-matt/

标签: woocommerce

解决方案


您必须使用woocommerce_display_product_attributes过滤器来删除空项目。我对空条件的假设是该值为零。您可以根据需要更改条件:

add_filter( 'woocommerce_display_product_attributes', 'ywp_hide_ptoperties_with_empty_values', 10, 2 );
function ywp_hide_ptoperties_with_empty_values( $attributes, $product ) {
    // Loop to check values
    foreach( $attributes as $attr ) {
        $new_attr   = array();

        // Your condition for check value is empty
        // You can use 'trim' etc.
        $value      = floatval( $attr['value'] );

        // Check value is 0 here means value is empty
        // and empty value skipped
        if( $value != 0 ) {
            $new_attr[] = $attr;
        }
    }

    return $new_attr;
}

此代码进入functions.php您的活动主题/子主题的文件。测试和工作。


推荐阅读