繁体   English   中英

WooCommerce 从商店页面中排除某些产品属性

[英]WooCommerce exclude certain product attributes from shop page

我一直在为这个而绞尽脑汁。 目前,要在商店页面上显示所有自定义产品属性(不要与产品页面混淆),我正在使用:

function show_attr() {
   global $product;
   echo '<div class="attributes">';
   $product->list_attributes();
   echo'</div>'
}

这很好用,并显示所有产品属性,但我只想包括某些属性。 我也试过听从这个人的建议:

<?php foreach ( $attributes as $attribute ) :
    if ( empty( $attribute['is_visible'] ) || 'CSC Credit' == $attribute['name'] || ( $attribute['is_taxonomy'] && ! taxonomy_exists( $attribute['name'] ) ) ) {
        continue;
    } else {
        $has_row = true;
    }
?>

所以不幸的是,这也不起作用。 我能卸下所需的属性,但它删除它在每一页上,我想只能从店铺页面排除。

我看到 $attribute 变量有这个[is_visible]条件。 有没有人知道如何删除商店页面上特定属性的内容? 我完全不知所措。 感谢您的任何帮助。

正如我在评论中提到的,您可以通过woocommerce_get_product_attributes过滤器控制任何给定产品的属性。 通过此过滤器的$attributes位于数组的关联数组中。 使用属性的“slug”作为数组键。 例如, var_dump()可能会显示以下$attributes

array (size=1)
  'pa_color' => 
    array (size=6)
      'name' => string 'pa_color' (length=8)
      'value' => string '' (length=0)
      'position' => string '0' (length=1)
      'is_visible' => int 0
      'is_variation' => int 1
      'is_taxonomy' => int 1

如果属性是分类法,则 slug 将以“pa_”开头,我一直认为它代表产品属性。 不是分类法的属性将仅具有 slug 的名称,例如:“大小”。

使用WooCommerce条件标签,你可以专门针对在店铺页面上的属性。

以下是两个示例过滤器,第一个用于排除特定属性:

// Exclude a certain product attribute on the shop page
function so_39753734_remove_attributes( $attributes ) {

    if( is_shop() ){
        if( isset( $attributes['pa_color'] ) ){
            unset( $attributes['pa_color'] );
        }
    }

    return $attributes;
}
add_filter( 'woocommerce_product_get_attributes', 'so_39753734_remove_attributes' );

后者用于根据您希望包含的属性构建自定义属性列表。

// Include only a certain product attribute on the shop page
function so_39753734_filter_attributes( $attributes ) {

    if( is_shop() ){
        $new_attributes = array();

        if( isset( $attributes['pa_color'] ) ){
            $new_attributes['pa_color'] = $attributes['pa_color'] ;
        }

        $attributes = $new_attributes;

    }

    return $attributes;
}
add_filter( 'woocommerce_product_get_attributes', 'so_39753734_filter_attributes' );

由于woocommerce_get_product_attributes已被弃用,因此在 2018 年 3 月 29 日更新woocommerce_product_get_attributes

试试这个!

<?php
if (is_page('shop')) {
    foreach ( $attributes as $attribute ) :
        if ( empty( $attribute['is_visible'] ) || 'CSC Credit' == $attribute['name'] || ( $attribute['is_taxonomy'] && ! taxonomy_exists( $attribute['name'] ) ) ) {
            continue;
        } else {
            $has_row = true;
        }
    }
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM