在 Woocommerce 存档页面中显示特定的产品属性

Display specific product attribute in Woocommerce archive pages

我一直在四处寻找,试图找到这个问题的答案,但还没有成功。基本上,我想在存档/商店页面上的产品标题下显示一些元数据。我的属性是 'colors',所以在尝试各种代码后,我想出了这个:

add_action( 'woocommerce_after_shop_loop_item', 'acf_template_loop_product_meta', 20 );

function acf_template_loop_product_meta() {

    echo '<h4>Color:' . get_field( '$colors = $product->get_attribute( 'pa_colors' )' .'</h4>';
    echo '<h4>Length:' . get_field( 'length' ) . '</h4>';
    echo '<h4>Petal Count:' . get_field( 'petal_count' ) . '</h4>';
    echo '<h4>Bud Size:' . get_field( 'bud_size' ) . '</h4>';
}

最后三行代码与高级自定义字段有关,它们都可以完美运行。这是一个试图获得我遇到问题的颜色属性的人。显示它的正确代码是什么?

首先,如果您使用 WC_Product 实例对象,您需要在使用任何 WC_Product 方法 之前调用它并检查它。

get_field( '$colors = $product->get_attribute( 'pa_colors' )'总是会报错。或者您使用 ACF 字段或获取要显示的产品属性 "pa_colors" 值。

尝试以下操作:

add_action( 'woocommerce_after_shop_loop_item', 'acf_template_loop_product_meta', 20 );
function acf_template_loop_product_meta() {
    global $product;

    // Check that we got the instance of the WC_Product object, to be sure (can be removed)
    if( ! is_object( $product ) ) { 
        $product = wc_get_product( get_the_id() );
    }

    echo '<h4>Color:' . $product->get_attribute('pa_colors') .'</h4>';
    echo '<h4>Length:' . get_field('length') . '</h4>';
    echo '<h4>Petal Count:' . get_field('petal_count') . '</h4>';
    echo '<h4>Bud Size:' . get_field('bud_size') . '</h4>';
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。它应该有效。