2

I have tried to display woocommerce categories thumbnails, but nothing works, below is the code to display the categories list and it works awesomely, just one thing left the thumbnails.

$product_cats = get_terms([
    'taxonomy'   => 'product_cat', 
    'hide_empty' => true, 
    'parent'     => 0, 
    'fields'     => 'names' // Term names
]);

foreach ( $product_cats as $key => $parent_term_name ) {
    printf( '<button class="tablinks %s" onclick="%s">%s</button>',
        $key === 0 ? esc_attr( 'active' ) : '',
        "myFunction(event,'{$parent_term_name})",
        $parent_term_name
    );
}

I have tried to add this part so that I could display the image, but nothing works beside from the placeholder image.

$category_thumbnail = get_woocommerce_term_meta($parent_term_name->term_id, 'thumbnail_id', true);
   if ( $category_thumbnail ) { 
       $image = wp_get_attachment_url($category_thumbnail);
    }
   else {
   $image = wc_placeholder_img_src();
}
2

To include the product category thumbnail (125 × 125 px) in your product category items (buttons), use the following:

$product_cats = get_terms([
    'taxonomy'   => 'product_cat',
    'hide_empty' => true,
    'parent'     => 0,
]);

foreach ( $product_cats as $key => $parent_term ) {
    $thumb_id = get_woocommerce_term_meta( $parent_term->term_id, 'thumbnail_id', true );
    $size     = 'thumbnail';
    $image    = wp_get_attachment_image_src($thumb_id, $size);

    printf( '<button class="tablinks %s" onclick="%s"><img src="%s" width="150" height="150" />%s</button>',
        $key === 0 ? esc_attr( 'active' ) : '',
        "myFunction(event,'{$parent_term->name}')",
        $thumb_id ? $image[0] : wc_placeholder_img_src($size),
        $parent_term->name
    );
}
  • Is there anyway to only show the first 6 or 7 categories from the list, if the list of parent categories is too long? @LoicTheAztec – Mitos May 12 at 15:56
  • 1
    @Mitos You can add in the get_term() function an additional argument (line): 'number' => 7, – LoicTheAztec May 12 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.