Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active January 15, 2023 22:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidsword/b33bbf37a5b9eb112e316b53bf6860e2 to your computer and use it in GitHub Desktop.
Save davidsword/b33bbf37a5b9eb112e316b53bf6860e2 to your computer and use it in GitHub Desktop.
WordPress - All filters to modify an images URL (as far as I could find)
<?php
// Images in post galleries
add_filter( 'get_post_galleries', '_img_url_filter', PHP_INT_MAX );
add_filter( 'widget_media_image_instance', '_img_url_filter', PHP_INT_MAX );
// Core image retrieval
add_filter( 'image_downsize', '_img_url_filter', 10, 3 );
// Responsive image srcset substitution
add_filter( 'wp_calculate_image_srcset', '_img_url_filter', 10, 5 );
add_filter( 'wp_calculate_image_sizes', '_img_url_filter', 1, 2 );
// Media Library - modal popup
add_filter('wp_prepare_attachment_for_js', '_img_url_filter', PHP_INT_MAX );
// Main get image
add_filter('wp_get_attachment_image', '_img_url_filter', PHP_INT_MAX );
add_filter('wp_get_attachment_image_src', '_img_url_filter', PHP_INT_MAX );
add_filter('wp_get_attachment_url', '_img_url_filter', PHP_INT_MAX );
// When using Insert Media pop-up
add_filter('image_send_to_editor', '_html_img_url_filter');
// content
add_action('the_content', '_html_img_url_filter');
// Jetpack
// add_filter( 'jetpack_photon_url', '_img_url_filter', 10, 3 );
// Advanced Custom Feilds
// add_filter('acf/fields/post_object/result','_html_img_url_filter');
// add_filter('acf/format_value', '_html_img_url_filter');
/**
* Filter Image URL.
*
* @param string $url of an image
* @return string
*/
function _img_url_filter($url) {
// ..do somthing with $url
return $url;
}
/**
* Extract and replace all URLs inside of an HTML string.
*
* Note this does not factor in external images. Domain check may be required.
*
* @param string $content HTML that may contain images.
* @return string HTML with possibly images that have been filtered
*/
function _html_img_url_filter($content) {
preg_match_all('/(\/\/\S+\.(?:jpg|png|gif))/', $content, $images);
foreach ($images[0] as $image) {
$new = _img_url_filter($image);
$content = str_replace($image,$new,$content);
}
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment