Search code examples
wordpresswoocommercewordpress-themingwoocommerce-theming

Change woocommerce images by image url from custom field


I am trying to build an affiliate website where I need to import 10.000+ products. I Use WP All Import and it gives me the option to download the pictures to my server. But you can imagine that all the pictures together fills the space that I have and makes my site and import slow.

I can save the image URL as a custom field and I want to use this URM in my img tag, but I have no idea how to accomplish this. I tried Googling, but I this my problem is too specifiek. I don't get all the cryptic code that build up the template. I thought it would be as easy as replacing the src of the img tag but I even can't find the img tag to do that. And I can imagine that if it's hard to find the img tag than it would be even harder to replace the src value by a custom field.

Can someone please tell me how I can accomplish my goal?


Solution

  • This is not well documented, but you can use the woocommerce_placeholder_img filter. This function will be called when there is no image attached to the Product.

    add_filter( 'woocommerce_placeholder_img', 'replace_woocommerce_image' );
    
    function replace_woocommerce_image( $size ) {
    
        //we will need access to the global post object
        //this way we know which product to replace for
        global $post;
    
        //check for the custom image url
        $src = get_post_meta( $post->ID, '_image_url', true );
    
        //if not image url is found, use the default
        if( ! $src )
            $src = wc_placeholder_img_src();
    
        return '<img src="' . $src . '" />';
    }
    

    You can see this in the codex here. It appears you can also use the woocommerce_placeholder_img_src filter, which would only filter the source url, as opposed to the entire <img> tag.

    Good luck!