Skip to content

Instantly share code, notes, and snippets.

@mckernanin
Created February 21, 2017 18:23
Show Gist options
  • Save mckernanin/c29950a9a977ff6dcfc96875f3ca50d4 to your computer and use it in GitHub Desktop.
Save mckernanin/c29950a9a977ff6dcfc96875f3ca50d4 to your computer and use it in GitHub Desktop.
Remote uploads function
<?php
define( 'LIVE_URL', 'http://yoursite.com')
// add_action('init', 'my_replace_image_urls' );
function my_replace_image_urls() {
$site_url = get_site_url();
if ( false !== strpos( $site_url, '.dev' ) ){
add_filter( 'wp_get_attachment_url', 'replace_dev_url', 10, 2 );
add_filter( 'wp_calculate_image_srcset', 'replace_dev_url_srcset', 10, 2 );
}
}
function replace_dev_url( $url, $post_id) {
$site_url = get_site_url();
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( $site_url, LIVE_URL, $url );
}
function replace_dev_url_srcset( $sources ) {
$site_url = get_site_url();
$filtered_sources = array();
foreach( $sources as $source_key => $source ) {
$source['url'] = str_replace( $site_url, LIVE_URL, $source['url']);
$filtered_sources[$source_key] = $source;
}
return $filtered_sources;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment