Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active July 14, 2022 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/026fd6962abccc83106dcab5bd186ab1 to your computer and use it in GitHub Desktop.
Save mishterk/026fd6962abccc83106dcab5bd186ab1 to your computer and use it in GitHub Desktop.
WordPress plugin for loading images from production on a staging/development website. See https://hookturn.io/load-media-images-from-production-wordpress-plugin/
<?php
/**
* Plugin Name: Load Images From Production (for staging/dev)
* Description: Hooks into WP's media URL generation and replaces the domain with the production domain.
* Author: Phil Kurth
* Author URI: https://hookturn.io
*/
// If this file is called directly, abort.
defined( 'WPINC' ) or die();
// Configure these
defined( 'LIFP_PRODUCTION_HOST' ) or define( 'LIFP_PRODUCTION_HOST', '' );
defined( 'LIFP_PRODUCTION_SCHEME' ) or define( 'LIFP_PRODUCTION_SCHEME', 'https' );
// If prod host name hasn't been defined, bail.
if ( empty( LIFP_PRODUCTION_HOST ) ) {
return;
}
add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size, $icon ) {
$parts = parse_url( $image[0] );
// Override with prod values.
$parts['scheme'] = LIFP_PRODUCTION_SCHEME;
$parts['host'] = LIFP_PRODUCTION_HOST;
// Ensure all keys are set.
$parts = array_merge( [ 'path' => '', 'query' => '' ], $parts );
// Build the new URL.
$image[0] = "{$parts['scheme']}://{$parts['host']}{$parts['path']}";
if ( $parts['query'] ) {
$image[0] .= '?' . $parts['query'];
}
return $image;
}, 10, 4 );
<?php
// Configure these in your wp-config.php file...
define( 'LIFP_PRODUCTION_HOST', 'www.mycoolsite.com' );
define( 'LIFP_PRODUCTION_SCHEME', 'https' ); // Optional.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment