<?php
/**
* Filter image attributes if the attachment parent post is woocommerce product then change its
* image attributes as desired.
*
* @param array $attr Attributes for the image markup.
* @param WP_Post $attachment Image attachment post.
* @param string|array $size Requested size. Image size or array of width and height values
* (in that order). Default 'thumbnail'.
* @return array $image Modified Image attributes
*/
function mxc_change_woocommerce_image_srcset( $attr, $attachment, $size ) {
global $post;
$attachment_id = $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 ( 'product' === get_post_type( $attachment->post_parent ) ) {
// Iterate to the current post attachment.
foreach ( get_attached_media( 'image', $attachment->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( $attr['src'], $upload_dir['baseurl'] ) || false !== strpos( $attr['srcset'], $upload_dir['baseurl'] ) ) {
// Remove base url to the image src.
$attr['src'] = str_replace( $upload_dir['baseurl'], $new_image_baseurl_src, $attr['src'] );
$attr['srcset'] = str_replace( $upload_dir['baseurl'], $new_image_baseurl_src, $attr['srcset'] );
if ( $remove_subdir ) {
$attr['src'] = str_replace( $upload_dir['subdir'], $new_image_subdir_src, $attr['src'] );
$attr['srcset'] = str_replace( $upload_dir['subdir'], $new_image_subdir_src, $attr['srcset'] );
}
}
}
}
}
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'mxc_change_woocommerce_image_srcset', 10, 3 );