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.
2
Answers
Just change
$cat->term_id
by$cat->parent
to get the parent thumbnail id.Final code :
Hope this helps
To avoid an empty image on the top level category use the following:
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.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.