Show icons or badges under title on product archives/category pages

So I was not able to solve my problem earlier, then I switched the plugin to “Category and Taxonomy Image” (by Aftab Hussain) and used the following code to display the icons on category/archive pages:

add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );
function attribute_img_loop() {
    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() );
    }

    $token_imgs = get_the_terms( get_the_ID(), 'pa_token' );

    foreach ( (array) $token_imgs as $token_img ) {
        $terms = $token_img->term_id;

        $meta_image = get_wp_term_image( $terms );
        echo '<ul><li><img src="' . $meta_image . '" class="tokenimg" /></li></ul>';
    }
}
  • pa_token is my attribute with sub-attributes/terms that have images.

  • foreach loop is used to output all the sub-attributes used per product, otherwise it will output only the first result.

  • (array) inside the foreach loop is used to not return anything if the value is null, otherwise all the other products with no attributes get an ugly PHP debug error on the main page.

Thanks for your help guys, for giving me the right direction.

Notes from Sally:

  1. I’d just remove the $product since you don’t really need it there because you used get_the_terms() and not a WooCommerce-specific function for getting the pa_token terms.

  2. I don’t recommend the (array) $token_imgs. Instead, make sure the $token_imgs is not a WP_Error instance and that it’s not an empty array.

  3. Instead of multiple ul (<ul><li></li></ul> <ul><li></li></ul> <ul><li></li></ul>...), I’d use multiple li (<ul><li></li> <li></li> <li></li>...</ul>). 🙂

So my code would be:

add_action( 'woocommerce_after_shop_loop_item', 'attribute_img_loop', 20 );
function attribute_img_loop() {
    $token_imgs = get_the_terms( get_the_ID(), 'pa_token' );
    if ( ! is_wp_error( $token_imgs ) && ! empty( $token_imgs ) ) {
        echo '<ul>';
        foreach ( $token_imgs as $term ) {
            $meta_image = get_wp_term_image( $term->term_id );
            echo '<li><img src="' . $meta_image . '" class="tokenimg" /></li>';
        }
        echo '</ul>';
    }
}