Skip to content

Instantly share code, notes, and snippets.

@chuckreynolds
Created April 3, 2015 06:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chuckreynolds/3ba095fb88bd4730ef93 to your computer and use it in GitHub Desktop.
Save chuckreynolds/3ba095fb88bd4730ef93 to your computer and use it in GitHub Desktop.
WordPress local dev environment plugin and config to use images from a live server instead of looking on local url path
<?php
/*
* Plugin Name: Local Dev Remote Images
* Description: this will allow a local dev environment to call all images in uploads from a remote server
* Version: 0.1
* License: GPL
* Author: @chuckreynolds
* Author URI: https://chuckreynolds.us
*/
add_action( 'init', 'ryno_localdev_remoteimages' );
function ryno_localdev_remoteimages() {
if ( defined('WP_SITEURL') && defined('REMOTE_SITEURL') ) {
if ( WP_SITEURL != REMOTE_SITEURL ){
add_filter('wp_get_attachment_url', 'ryno_localdev_remoteimages_get_attachment_url', 10, 2 );
}
}
}
function ryno_localdev_remoteimages_get_attachment_url( $url, $post_id) {
if ( $file = get_post_meta( $post_id, '_wp_attached_file', true) ) {
if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
if ( file_exists( $uploads['basedir'] .'/'. $file ) ) {
return $url;
}
}
}
return str_replace( WP_SITEURL, REMOTE_SITEURL, $url );
}
<?php
//* put this in wp-config.php
define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] .
str_replace(DIRECTORY_SEPARATOR, '/', str_replace(realpath($_SERVER['DOCUMENT_ROOT']), '', dirname(__FILE__))));
define('REMOTE_SITEURL', 'http://UrlToPullImagesFrom.com');
@jeremyescott
Copy link

So in the case of using a remote, and not local, development environment, this should work equally as well?

@chuckreynolds
Copy link
Author

@jeremyescott yup. it'll work fine. Just tells any request to the currently local site's /wp-content/uploads/ url to use the remote url instead. If the filenames are different it won't work. It's just replacing the domain with the remote domain.

@chuckreynolds
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment