获取产品定制属性以在WooCommerce产品循环中显示它们 [英] Get product custom attributes to display them in WooCommerce product loop

查看:36
本文介绍了获取产品定制属性以在WooCommerce产品循环中显示它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WooCommerce网站(房地产)工作,我不能在我的首页上显示产品定制属性(例如。平方米、房间、厕所等)。我正在尝试使用下面的代码,但我可以让它工作。使用我拥有的代码,我只能显示产品ID,但当我将属性ID放入代码中时,它只显示单词&或数组。

这是我的代码:

add_action('woocommerce_after_shop_loop_item_title', 'cstm_display_product_category', 5);

function cstm_display_product_category()
{
    global $product;

    $productAttribute = $product->get_id();

   //if(isset($productAttribute)){
       echo '<div class="items" style="color: #fff;"><p>Output: ' . $productAttribute . '</p></div>';
   //}
}

您可以看到实时输出here

无论你能给我什么帮助或指导来实现这一点,我都会非常感激。在这件事上我是新手。

P.D.我正在将此代码插入到函数.php文件中。

WordPress是最新的。 WooCommerce是最新的。

推荐答案

更新3

对于产品属性(自定义或非定制),您可以使用WC_Product方法get_attribute(),您可以在其中输入属性名称、插件或分类。因此,在您的代码中:

add_action('woocommerce_after_shop_loop_item_title', 'display_custom_product_attributes_on_loop', 5 );
function display_custom_product_attributes_on_loop() {
    global $product;

    $value1 = $product->get_attribute('Square meters');
    $value2 = $product->get_attribute('Rooms');
    $value3 = $product->get_attribute('Toilets');

    if ( ! empty($value1) || ! empty($value2) || ! empty($value3) ) {

        echo '<div class="items" style="color: red;"><p>';

        $attributes = array(); // Initializing

        if ( ! empty($value1) ) {
            $attributes[] = __("Square meters:") . ' ' . $value1;
        }

        if ( ! empty($value2) ) {
            $attributes[] = __("Rooms:") . ' ' . $value2;
        }

        if ( ! empty($value3) ) {
            $attributes[] = __("Toilets:") . ' ' . $value3;
        }

        echo implode( '<br>', $attributes ) . '</p></div>';
    }
}

代码放在活动子主题(或活动主题)的函数.php文件中。已测试并正常工作。


从产品属性名称的简单数组自动编写代码:

下面的代码将产生相同的输出,但它经过压缩、优化,并且只需要您想要的产品属性的数组:

add_action('woocommerce_after_shop_loop_item_title', 'display_custom_product_attributes_on_loop', 5 );
function display_custom_product_attributes_on_loop() {
    global $product;

    // Settings: Here below set your product attribute label names
    $attributes_names = array('Square meters', 'Rooms', 'Toilets');

    $attributes_data  = array(); // Initializing

    // Loop through product attribute settings array
    foreach ( $attributes_names as $attribute_name ) {
        if ( $value = $product->get_attribute($attribute_name) ) {
            $attributes_data[] = $attribute_name . ': ' . $value;
        }
    }

    if ( ! empty($attributes_data) ) {
        echo '<div class="items" style="color: red;"><p>' . implode( '<br>', $attributes_data ) . '</p></div>';
    }
}

代码放在活动子主题(或活动主题)的函数.php文件中。已测试并正常工作。

这篇关于获取产品定制属性以在WooCommerce产品循环中显示它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆