Last active
July 14, 2022 06:26
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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