Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show WooCommerce parent category thumbnail when viewing a child category

I have a function that returns the product Category Thumbnail on the Archive pages for WooCommerce. This is working great.

What I would like to do, is be able to return the Parent Category Thumbnail when viewing Child Categories.

Here is the code I've currently got:

function woocommerce_category_image() {
    if ( is_product_category() ){
        global $wp_query;
        $cat = $wp_query->get_queried_object();
        $thumbnail_id = get_term_meta( $cat->term_id, 'thumbnail_id', true );
        $image = wp_get_attachment_url( $thumbnail_id );
        if ( $image ) {
            echo '<img src="' . $image . '" alt="' . $cat->name . '" />';
        }
    }
}

Can anybody help modify the query so that it shows the parent category image.

Ideally even better still would be to show the child thumbnail if there is one, and if there isn't, then drop back to the parent one and show that.

like image 749
CS10 Avatar asked Jan 18 '26 08:01

CS10


1 Answers

To avoid an empty image on the top level category use the following:

function woocommerce_category_image() {
    if ( is_product_category() ){
        $term      = get_queried_object(); // get the WP_Term Object
        $term_id   = $term->parent > 0 ? $term->parent : $term->term_id; // Avoid an empty image on the top level category
        $image_src = wp_get_attachment_url( get_term_meta( $term_id, 'thumbnail_id', true ) ); // Get image Url
    
        if ( ! empty($image_src) ) {
            echo '<img src="' . $image_src . '" alt="' . $term->name . '" />';
        }
    }
}

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


Update (related to your comment)

Here if the queried product category has not an image set for it, the parent product category image will be displayed instead.

function woocommerce_category_image() {
    if ( is_product_category() ){
        $term      = get_queried_object(); // get the WP_Term Object
        $image_id  = get_term_meta( $term->term_id, 'thumbnail_id', true );
        
        if( empty( $image_id ) && $term->parent > 0 ) {
            $image_id  = get_term_meta( $term->parent, 'thumbnail_id', true );
        }
        $image_src = wp_get_attachment_url( $image_id ); // Get the image Url
    
        if ( ! empty($image_src) ) {
            echo '<img src="' . $image_src . '" alt="' . $term->name . '" />';
        }
    }
}

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

like image 139
LoicTheAztec Avatar answered Jan 20 '26 01:01

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!