<?php
/**
* Filter image src if the attachment parent post is woocommerce product then change its
* image src as desired.
*
* @param array|false $image
* @param int $attachment_id
* @param string|array $size
* @param bool $icon
* @return void
*/
function mxc_change_woocommerce_image_src( $image, $attachment_id, $size, $icon ) {
$image_object = get_post( $attachment_id );
$upload_dir = wp_upload_dir();
$remove_subdir = false; // IMPORTANT: Change to false if you want subdir to remain in the image src / srcset.
$new_image_baseurl_src = 'https://desired-url.com/wp-content/uploads'; // IMPORTANT: Change this to the desired image url.
$new_image_subdir_src = ''; // Example Value '/2018/05'.
if ( $image ) {
if ( 'product' === get_post_type( $image_object->post_parent ) ) {
// Iterate to the current post attachment.
foreach ( get_attached_media( 'image', $image_object->post_parent ) as $image_attachment ) {
// if the image is attached to a product post type change its url to desired url.
if ( (int) $attachment_id === $image_attachment->ID ) {
// Make sure that we have b$upload_dir['baseurl'] in the image src / srcset.
if ( false !== strpos( $image[0], $upload_dir['baseurl'] ) ) {
// Remove base url to the image src.
$image[0] = str_replace( $upload_dir['baseurl'], $new_image_baseurl_src, $image[0] );
if ( $remove_subdir ) {
$image[0] = str_replace( $upload_dir['subdir'], $new_image_subdir_src, $image[0] );
}
}
}
}
}
}
return $image;
}
add_filter( 'wp_get_attachment_image_src', 'mxc_change_woocommerce_image_src', 10, 4 );
// apply_filters( 'wp_get_attachment_image_src', array|false $image, int $attachment_id, string|array $size, bool $icon );
// https://developer.wordpress.org/reference/hooks/wp_get_attachment_image_src/