Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created November 5, 2020 20:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yanknudtskov/77e83bb538fc43baae9cae978c818d03 to your computer and use it in GitHub Desktop.
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
<?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