goranseric
11/18/2016 - 10:59 AM

WordPress local dev environment plugin and config to use images from a live server instead of looking on local url path

WordPress local dev environment plugin and config to use images from a live server instead of looking on local url path

<?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');
<?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 );
}