mark5 mark5 - 5 months ago 22
PHP Question

WooCommerce Display Custom Taxonomy in archive

Trying to show the custom taxonomy "w_label" which I registered under products. However when I tried to display it with the code below:

register_taxonomy('w_label', array('product'),
array(
'hierarchical' => true,
'label' => 'Product Labels',
'singular_label' => 'Product Label',
'rewrite' => true,
'supports' => array('excerpt', 'thumbnail')

)
);

function w_label_name () {
global $post;
$terms = get_the_terms( $post->ID, 'w_label' );
foreach ( $terms as $term ){
echo '<div class="label">' . $term->name . '</div>';
}

}
add_action( 'woocommerce_before_shop_loop_item_title', 'w_label_name', 2 );


I keep getting "Warning: Invalid argument supplied for foreach()"

Not sure what I've missed. If I use this code for the default WooCommerce category it works, but not for custom taxonomy that I've registered here.

Answer

First try to see if there is not a problem with $terms = get_the_terms($post->ID, 'w_label'); try in your function this, to display $terms:

function w_label_name () {
    global $post;
    $terms = get_the_terms( $post->ID, 'w_label' );
    echo '<div class="label">' . var_dump($terms) . '</div>';
}

Then try also get_terms( 'w_label' ); instead of get_the_terms( $post->ID, 'w_label' ); and echo also var_dump($terms) with that to see what you are getting.

If you get something, the problem is coming from $term->name and the manner to get $terms. Then you could try this (without any guaranty, because untested):

function w_label_name () {
    global $post;
    $terms = get_terms( 'w_label' );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
        foreach ( $terms as $term ) {
            echo '<div class="label">' . $term->name . '</div>';
        }
    }
}
add_action( 'woocommerce_before_shop_loop_item_title', 'w_label_name', 10 );
Comments