首页 文章

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

提问于
浏览
1

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

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

1 回答

  • 0

    首先,如果您使用 WC_Product 实例对象,则需要在使用任何 WC_Product method 之前调用它并进行检查 .

    并且 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文件中 . 它应该工作 .

相关问题