【问题标题】:Display product attributes values for specific categories in WooCommerce product loops在 WooCommerce 产品循环中显示特定类别的产品属性值
【发布时间】:2021-06-13 12:28:28
【问题描述】:

我正在 WP + WooCommerce 中建立商店。我有不同类型的产品类别,如光盘和包。对于光盘产品,我有一些特定的属性,例如 Speed、Glide、Turn 和 Fade,这些属性没有任何其他产品类别。我只想在商品图片下的店铺页面上显示这些商品属性值。

我找到了一个代码,我给自己添加了一个分隔符号“|”,但是这个分隔符号现在显示在所有可变的产品下。

是否可以不将代码更改为变量而仅针对特定产品类别和子类别?

代码:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_size_attribute', 5 );

function display_size_attribute() {
    global $product;
    
    if ( $product->is_type('variable') ) {
        
        $taxonomy = 'pa_speed';
        echo '<span class="attribute-speed">' . $product->get_attribute($taxonomy) . '</span>' ;
        echo ' | ';
        $taxonomy = 'pa_Glide';
        echo '<span class="attribute-Glide">' . $product->get_attribute($taxonomy) . '</span>';
        echo ' | ';
        $taxonomy = 'pa_Turn';
        echo '<span class="attribute-Turn">' . $product->get_attribute($taxonomy) . '</span>';
        echo ' | ';
        $taxonomy = 'pa_Fade';
        echo '<span class="attribute-Fade">' . $product->get_attribute($taxonomy) . '</span>';
    }
}

【问题讨论】:

  • 在评论区我的答案下方添加评论,如果你想说点什么,如果你想让我得到通知。

标签: php wordpress woocommerce product taxonomy-terms


【解决方案1】:

仅当变量存在于您的可变产品上时,才使用以下重新访问的代码来获取单独的属性值:

add_action( 'woocommerce_before_shop_loop_item_title', 'display_some_attributes', 5 );
function display_some_attributes() {
    global $product;

    if ( $product->is_type('variable') ) {
        $attributes = array('speed', 'Glide', 'Turn', 'Fade'); // here you defined attribute slugs
        $output     = array(); // Initializing

        // Loop through product attributes
        foreach ( $attributes as $attribute ) {
            $taxonomy = 'pa_' . $attribute;
            $values   = $product->get_attribute($taxonomy);

            // If not empty add it to the array
            if ( ! empty($values) ) {
                $output[] = '<span class="attribute-' . $attribute . '">' . $values . '</span>';
            }
        }
        // Convert array to a separated string by pipes
        echo implode(' | ', $output);
    }
}

要仅针对特定产品类别,请在代码中替换块:

    global $product;

    if ( $product->is_type('variable') ) {

with (您将在其中定义产品类别术语)

    global $product;

    $categories = array( 'cats', dogs' ); // Here your category terms ids, slugs or names

    if ( $product->is_type('variable') && has_term( $categories, 'product_cat', $product->get_id() ) ) {

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

【讨论】:

  • 我的代码显示任何非空属性值,包括“0”,因为我使用empty(),所以空是null''(一个空字符串)...
  • 感谢您的支持。一切运行良好,但不知何故,如果它是 0(零),它就不会显示该值。例如,我将属性“Turn”设置为 0,但它不显示。截图 - imgur.com/a/C6UtUvP
猜你喜欢
  • 2017-03-27
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
相关资源
最近更新 更多