Site logo

Archived topic

Woocommerce category image on single product

5 replies · Started by Wim on January 14, 2019

Viewing posts 1–6 of 6

Took a look at the examples of elements and page headers, but no result for the moment.
I would like each product to have a fullwidth hero banner with the image of its category.
What shortcode could be made/inserted in the element in order to get this done?
Thanks a million!

Hi there,

Give this function a shot:

add_filter( 'generate_page_hero_background_image_url', function( $url ) {
    if ( function_exists( 'is_product' ) && function_exists( 'get_woocommerce_term_meta' ) && is_product() ) {
        $terms =  get_the_terms( get_the_ID(), 'product_cat' );
        $thumbnail_id = false;

        if ( $terms && ! is_wp_error( $terms ) ) {
            $id = $terms[0]->term_id;
            $thumbnail_id = get_woocommerce_term_meta( $id, 'thumbnail_id', true );
        }

        if ( $thumbnail_id ) {
            $url = wp_get_attachment_url( $thumbnail_id );
        }
    }

    return $url;
} );

Let me know :)

Thanks Tom. Took me some tries to get this working - changed it into add_shortcode, put it into functions.php.
Inserted the shortcode into a new element between two img tags and got the image.
<img src="[generate_page_hero_background_image_url]">
But of course, this is no hero banner.
Is there any way to override the page hero background image with this one, and still use the padding, alignment, ...?
Thank you.

Did my code above not work? It should replace the background image you have set with the product category image.

Hi Tom, got it working through functions.php and a new element - don't know why it gave me issues.
What I did encounter was that {{post_terms.taxonomy}} on the page hero gives me:
Recoverable fatal error: Object of class WP_Error could not be converted to string in /app/public/wp-content/plugins/gp-premium/elements/class-hero.php on line 848
The title, author and other template tags work just fine.

But okay, solved it with {{post_terms.product_cat}}, probably because it was a product ;)

Ah yes, taxonomy needs to be replaced with the actual taxonomy name.

Glad you got it working! :)

This archived topic is closed to new replies.