Created
March 18, 2019 01:27
-
-
Save ChrisHardie/d2bcc0543b7559d26070d017d1e8e1a9 to your computer and use it in GitHub Desktop.
Example WordPress plugin to help simplify attachment URLs on multisite sites with mapped domains
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 | |
/** | |
* Plugin Name: Multisite Domain Mapping Attachment URL Fixes | |
* Description: Update attachment URLs to use mapped domain and remove mention of "sites" path. | |
* Author: Chris Hardie | |
* | |
* Rewrite attachment URLs (and related srcset URLs) to the non-multisite, mapped domain version if a domain is mapped | |
* Requires that the related nginx config that maps the non-multisite URL to the multisite URL be in place | |
**/ | |
add_filter( 'wp_get_attachment_url', 'jch_attachment_url_with_domain_mapping' ); | |
function jch_attachment_url_with_domain_mapping( $attachment_url ) { | |
global $wpdb; | |
// Comes from https://wordpress.org/plugins/wordpress-mu-domain-mapping/ | |
if ( function_exists( 'get_original_url' ) && function_exists( 'domain_mapping_siteurl' ) ) { | |
$orig_url = get_original_url( 'siteurl' ); | |
$mapped_url = domain_mapping_siteurl( 'NA' ); | |
if ( 'NA' !== $mapped_url ) { | |
if ( ! empty( $orig_url ) && ( $orig_url !== $mapped_url ) ) { | |
$attachment_url = str_replace( $orig_url, $mapped_url, $attachment_url ); | |
} | |
$attachment_url = preg_replace( '!wp-content/uploads/sites/\d+/!', 'wp-content/uploads/', $attachment_url ); | |
} | |
} | |
return $attachment_url; | |
} | |
add_filter( 'wp_calculate_image_srcset', 'jch_srscet_urls_with_domain_mapping' ); | |
function jch_srscet_urls_with_domain_mapping( $sources ) { | |
if ( function_exists( 'domain_mapping_siteurl' ) ) { | |
$domain_mapped_url = domain_mapping_siteurl( 'NA' ); | |
if ( 'NA' !== $domain_mapped_url ) { | |
foreach ( $sources as $source ) { | |
if ( ! empty( $source['url'] ) && ! empty( $source['value'] ) ) { | |
$sources[ $source[ 'value' ] ][ 'url' ] = preg_replace( '!wp-content/uploads/sites/\d+/!', 'wp-content/uploads/', $sources[ $source[ 'value' ] ][ 'url' ] ); | |
} | |
} | |
} | |
} | |
return $sources; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment