Skip to content

Instantly share code, notes, and snippets.

@bacoords
bacoords / use-remote-media.php
Last active July 21, 2023 17:21 — forked from kingkool68/use-remote-media.php
Check if a local file exists in the WordPress media library and if it doesn't exist, replace the URL with a different URL. Helpful when working with a local site that doesn't have all of the media downloaded as the production site. See https://localwp.com/community/t/proxying-requests-to-wp-content-uploads-to-a-production-site/15701
<?php
// Put this in wp-config.php and replace https://example.com/ with the URL of the production site.
define( 'BC_USE_REMOTE_MEDIA_URL', 'https://example.com' );
// Put the rest of this in functions.php or a custom plugin or somewhere else.
if ( defined( 'BC_USE_REMOTE_MEDIA_URL' ) && ! empty( BC_USE_REMOTE_MEDIA_URL ) ) {
add_filter( 'wp_get_attachment_image_src', 'bc_filter_wp_get_attachment_image_src' );
add_filter( 'wp_calculate_image_srcset', 'bc_filter_wp_calculate_image_srcset' );
add_filter( 'wp_get_attachment_url', 'bc_filter_wp_get_attachment_url' );
}