Skip to content
Advertisement

Get the product ID in woocommerce_product_get_image filter hook

Some of our products are using an external image instead of the post thumbnail, I have an acf set up for this url. It appears that you can filter the woocommerce get_image() function, but I can’t find a way to get the current product’s id to get the field.

Here’s what I have so far:

function offsite_product_images($image_url, //variable $this wont work here){
    //need some way to get the current product's id
    if(get_field('thumbnail_url', $id)){
        $image_url = get_field('thumbnail_url', $id);
    }
    return $image_url;
}
add_filter( 'woocommerce_product_get_image', 'offsite_product_images');

the woocommerce get_image() function:

public function get_image( $size = 'woocommerce_thumbnail', $attr = array(), $placeholder = true ) {
    if ( has_post_thumbnail( $this->get_id() ) ) {
        $image = get_the_post_thumbnail( $this->get_id(), $size, $attr );
    } elseif ( ( $parent_id = wp_get_post_parent_id( $this->get_id() ) ) && has_post_thumbnail( $parent_id ) ) {
        $image = get_the_post_thumbnail( $parent_id, $size, $attr );
    } elseif ( $placeholder ) {
        $image = wc_placeholder_img( $size );
    } else {
        $image = '';
    }

    return apply_filters( 'woocommerce_product_get_image', wc_get_relative_url( $image ), $this, $size, $attr, $placeholder, $image );
}

I even tried changing the function to pass the id directly, but it wouldn’t do it.

Any help on getting the product or it’s id passed to my filter would be greatly appreciated.

Advertisement

Answer

Your function code is incomplete, there is some missing arguments as the WC_Product object, that you need to get the product ID. Try the following:

add_filter( 'woocommerce_product_get_image', 'offsite_product_images', 10, 5 );
function offsite_product_images( $image, $product, $size, $attr, $placeholder ){
    if( get_field('thumbnail_url', $product->get_id() ) ){
        $image = get_field('thumbnail_url', $product->get_id() );
    }
    return $image;
}

Code goes in functions.php file of your active child theme (or active theme). It should work.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement