Shortcode to display WooCommerce product category thumbnail in any theme

62 views Asked by At

I would like to display the category thumbnail on my category page with a short code. Forgive me, I have very poor skills in PHP...

About the system : Wordpress 6.4.3 woocommerce 8.6.1 Theme : Divi 4.24.2

I found this topic, which helped me a lot : How to display Woocommerce category description with DIVI theme

I would like a similar code, but for displaying the active category thumbnail.

I tried to add this to functions.php, but not a success :

add_shortcode('cat_img', 'cat_img_shortcode');
function cat_img_shortcode() {
    
    global $wp_query;
    $cat = $wp_query->get_queried_object();
    
    if( $cat == null ) return;

    $output = nl2br($cat->thumbnail);
    return $output;
}

if someone could help me this would be wonderful :)

1

There are 1 answers

0
LoicTheAztec On

You can use the following shortcode to display the product category image on product category archive pages, if available:

add_shortcode('term_img', 'term_image_shortcode');
function term_image_shortcode() {
    $term = get_queried_object();
    
    if( ! is_a($term, 'WP_Term') ) return;

    $thumbnail_id = get_term_meta( $term->term_id, 'thumbnail_id', true );

    if ( ! $thumbnail_id ) return;

    $image_size   = 'woocommerce_thumbnail';
    $image        = wp_get_attachment_image_src( $thumbnail_id, $image_size );
    $image        = str_replace( ' ', '%20', $image[0] ); // Prevent esc_url from breaking spaces in urls for image embeds.

    if ( ! $image ) return;

    $dimensions   = wc_get_image_size( $image_size );
    $image_srcset = wp_get_attachment_image_srcset( $thumbnail_id, $image_size );
    $image_sizes  = wp_get_attachment_image_sizes( $thumbnail_id, $image_size );

    // Add responsive image markup if available.
    if ( $image_srcset && $image_sizes ) {
        return '<img src="' . esc_url( $image ) . '" alt="' . esc_attr( $term->name ) . '" width="' . esc_attr( $dimensions['width'] ) . '" height="' . esc_attr( $dimensions['height'] ) . '" srcset="' . esc_attr( $image_srcset ) . '" sizes="' . esc_attr( $image_sizes ) . '" />';
    } else {
        return '<img src="' . esc_url( $image ) . '" alt="' . esc_attr( $term->name ) . '" width="' . esc_attr( $dimensions['width'] ) . '" height="' . esc_attr( $dimensions['height'] ) . '" />';
    }
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

Usage: [term_image]