Adam Bell
Adam Bell

Reputation: 1045

Display specific product attribute in Woocommerce archive pages

I've been looking around SO trying to find an answer to this, but no luck yet. Basically, I want to display some meta data under the title of my products on the archive / shop page(s). My attribute is 'colors', so after trying various pieces of code, I came up with this:

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>';
}

The last three lines of code relate to Advanced Custom Fields, and they all work perfectly. It's the one trying to get the color attribute I'm having the issue with. What would be the correct code to display that?

Upvotes: 1

Views: 3872

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

First if you use the WC_Product instance object, you need to call it and check it before using any WC_Product method on it.

And get_field( '$colors = $product->get_attribute( 'pa_colors' )' will always throw an error. Or you use an ACF field or you get the product attribute "pa_colors" values to be displayed.

Try the following:

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>';
}

Code goes in function.php file of your active child theme (or active theme). It should works.

Upvotes: 2

Related Questions