Created
November 5, 2020 20:37
-
-
Save yanknudtskov/77e83bb538fc43baae9cae978c818d03 to your computer and use it in GitHub Desktop.
A relatively simple way to replace URL for media files in WordPress when running a Staging environment
This file contains 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 | |
define( 'STAGING_URL', 'https://staging.mysiteurl.com'); | |
define( 'PRODUCTION_URL', 'https://www.mysiteurl.com'); | |
add_filter( 'wp_get_attachment_url', 'yanco_staging_wp_get_attachment_url', 1000000, 2 ); | |
function yanco_staging_wp_get_attachment_url( $url, $attachment ) | |
{ | |
if( strpos( $url, STAGING_URL ) !== false ) { | |
$url = str_replace( STAGING_URL, PRODUCTION_URL, $url ); | |
} | |
return $url; | |
} | |
add_filter( 'wp_get_attachment_image_attributes', 'yanco_staging_wp_get_attachment_image_attributes' ); | |
function yanco_staging_wp_get_attachment_image_attributes($attributes) | |
{ | |
if ( isset( $attributes['src'] ) ) { | |
if( strpos( $attributes['src'], STAGING_URL ) !== false ) { | |
$attributes['src'] = str_replace( STAGING_URL, PRODUCTION_URL, $attributes['src'] ); | |
} | |
} | |
if ( isset( $attributes['srcset'] ) ) { | |
if( strpos( $attributes['srcset'], STAGING_URL ) !== false ) { | |
$attributes['srcset'] = str_replace( STAGING_URL, PRODUCTION_URL, $attributes['srcset'] ); | |
} | |
} | |
return $attributes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment