Site logo

Archived topic

WooCommerce Archives: Change onHover image from [0]->[1] to [0]->[n]?

3 replies · Started by Joseph on October 31, 2021

Viewing posts 1–4 of 4

Hey!

I'm looking to change...
Layout -> WooCommerce -> Display Secondary Image on hover
...to an image in the archive of my choosing. For example, we run our Product shots as images [0], [1], and [2], and our lifestyle shots as [3] and [4]. We'd like to change the onHover from the secondary image [1] to a lifestyle image [3].

Found this on StackOverflow, and I know it's somewhat close hooking into woocommerce_before_shop_loop_item_title with wc_get_product()->get_gallery_image_ids()

Anyway, wondering if you guys could help. I don't know where to hook into, or what action to remove/add.

Thanks!

Hi there,

not 100% sure on this, but if you disable the Display Secondary Image on Hover in Customizer > Layout > Woocommerce. Then we can hook in our own custom function like so:

add_action( 'woocommerce_before_shop_loop_item_title', 'custom_wc_secondary_product_image' );

function custom_wc_secondary_product_image() {
    $post_type = get_post_type( get_the_ID() );
    
    if ( 'product' === $post_type && method_exists( 'WC_Product', 'get_gallery_image_ids' ) ) {
        $product = wc_get_product( get_the_ID() );
        $attachment_ids = $product->get_gallery_image_ids();
        
        if ( $attachment_ids && generatepress_wc_get_setting( 'product_archive_image' ) && has_post_thumbnail() ) {
            // Check if alternative gallery image [1] exists
            if (!empty($attachment_ids['1'])) {
                // If gallery image [1] exists load this
                $secondary_image_id = $attachment_ids['1'];
            } else {
                // if NOT then load the default [0] image
                $secondary_image_id = $attachment_ids['0'];
            }
            
            echo wp_get_attachment_image( $secondary_image_id, 'shop_catalog', '', $attr = array( 'class' => 'secondary-image attachment-shop-catalog' ) );
        }
    }
}

I have commented where the alternative gallery image is checked for and loaded.
By default the first image in the get_gallery_image_ids() is used ie. $attachment_ids['0'] so in the condition above you can choose the alternative ID eg. $attachment_ids['1']

It will need some CSS to create the hover overlay but if the above works i can assist with that.

Doc on how to add PHP: https://docs.generatepress.com/article/adding-php/

Hey David,

That code worked perfectly! Took care of the CSS, all set :-)

Thanks a ton!

Joseph

Awesome - glad to hear that worked!

This archived topic is closed to new replies.