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

问题描述 投票:1回答:1

我一直在四处寻找,试图找到答案,但还没有运气。基本上,我想在存档/商店页面上的产品标题下显示一些元数据。我的属性是'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>';
}

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

php wordpress woocommerce advanced-custom-fields custom-taxonomy
1个回答
0
投票

首先,如果你使用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文件中。它应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.