php - 获取并显示 WooCommerce 中产品属性的值

标签 php wordpress woocommerce attributes product

在 WooCommerce 中,我有以下代码可以在商店页面等文件页面上显示产品属性标签:

if (!function_exists('shop_attributes_in_loop')) {
    function shop_attributes_in_loop(){
        global $product;
        $attributes = $product->get_attributes();
        if(!empty($attributes)){
            $attribute_single = array_keys($attributes);
            $myArray = array();
            echo '<div class="product_attributes">';
            foreach ($attribute_single as $attribute => $value) {
                $myArray[] = ucfirst($value);
            }
            echo implode(', ', $myArray).'</div>';
        }
    }
}
add_action('woocommerce_after_shop_loop_item', 'shop_attributes_in_loop');

它们仅将属性字段名称显示为 pa_sizepa_color

如何获取并显示该产品属性的值(例如 2kg3kg 或 <强>蓝色绿色)?

谢谢。

最佳答案

这段代码很简单(示例 1):

function nt_product_attributes() {
global $product;
    if ( $product->has_attributes() ) {

        $attributes = ( object ) array (
        'color'              => $product->get_attribute( 'pa_color' ),
        'size'            => $product->get_attribute( 'pa_size' ),
        );
    return $attributes;
    }
}

用法:

$attributes = nt_product_attributes();
echo $attributes->color;
echo $attributes->size;

或(示例 2)

function nt_product_attributes() {
global $product;
    if ( $product->has_attributes() ) {

        $attributes = array (
        'color'              => $product->get_attribute('pa_color'),
        'size'            => $product->get_attribute('pa_size'),
        );
    return $attributes;
    }
}

用法:

$attributes = nt_product_attributes();
echo $attributes['color'];
echo $attributes['size'];

关于php - 获取并显示 WooCommerce 中产品属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393797/

相关文章:

php - 如何检查 fetch_assoc 循环中是否还有行?

wordpress - 我如何在 wordpress 的每个类别中只获得 1 个帖子

MySQL 截断不正确的 DOUBLE 值错误

php - WooCommerce:将端点分配给我的帐户页面中的自定义模板

wordpress - WooCommerce 图像缩略图相同大小

PHP 不显示任何类型的错误

php - 试图调用函数 "curl_init"

PHP 获取 url 中的 var1 + var2,例如 .php?=1something?=3

php - 如何在WordPress最近的帖子中添加导航?

php - 如何阻止菜单嵌套在 WordPress 的下拉菜单中