Last active
November 14, 2017 09:56
-
-
Save polevaultweb/eb6295b38c540dafec31 to your computer and use it in GitHub Desktop.
This file contains hidden or 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: WP Offload S3 - Relative URL Find & Replace | |
Description: Find and replace relative local URLs with S3 URLs in post content after they have been uploaded to S3 | |
Author: Delicious Brains | |
Version: 1.0 | |
Author URI: https://deliciousbrains.com/ | |
*/ | |
add_action( 'admin_init', 'wpos3rel_find_replace' ); | |
add_filter( 'query', 'wpos3rel_find_replace_strip_local_url' ); | |
/** | |
* Run a find and replace on all attachments uploaded to S3 | |
*/ | |
function wpos3rel_find_replace() { | |
if ( ! class_exists( 'Amazon_S3_And_CloudFront_Pro' ) ) { | |
return; | |
} | |
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { | |
return; | |
} | |
global $pagenow; | |
if ( 'post.php' === $pagenow ) { | |
// Don't run on the post page, creates a loop | |
return; | |
} | |
global $as3cfpro; | |
if ( ! $as3cfpro->get_setting( 'serve-from-s3' ) ) { | |
// Don't replace if we aren't rewriting URLs | |
return; | |
} | |
if ( ! get_site_option( 'wpos3rel_find_replace', false ) ) { | |
$blogs = $as3cfpro->get_blogs_data(); | |
// Get all uploaded S3 attachments IDs | |
foreach ( $blogs as $blog_id => $blog ) { | |
$attachments = $as3cfpro->get_all_s3_attachments( $blog['prefix'] ); | |
$as3cfpro->switch_to_blog( $blog_id ); | |
foreach ( $attachments as $attachment ) { | |
$as3cfpro->find_and_replace_attachment_urls( $attachment['post_id'] ); | |
} | |
} | |
$as3cfpro->restore_current_blog( $blog_id ); | |
// Make sure this doesn't get run again, unless we clear this option | |
update_site_option( 'wpos3rel_find_replace', true ); | |
} | |
} | |
/** | |
* Remove the site home URL from local URLs during find and replace | |
* so they become relative | |
* | |
* @param string $query | |
* | |
* @return string mixed | |
*/ | |
function wpos3rel_find_replace_strip_local_url( $query ) { | |
$callers = debug_backtrace(); | |
$parent_method = false; | |
$child_method = false; | |
foreach ( $callers as $caller ) { | |
if ( isset( $caller['function'] ) && 'wpos3rel_find_replace' === $caller['function'] ) { | |
$parent_method = true; | |
} | |
if ( isset( $caller['function'] ) && 'process_pair_replacement' === $caller['function'] ) { | |
$child_method = true; | |
} | |
} | |
if ( $parent_method && $child_method ) { | |
// Remove the root URL of the site from any local URL being replaced | |
$query = str_replace( untrailingslashit( network_home_url() ), '', $query ); | |
} | |
return $query; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. Is this only applicable for Pro version?