Skip to content

Instantly share code, notes, and snippets.

@polevaultweb
Last active November 14, 2017 09:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polevaultweb/eb6295b38c540dafec31 to your computer and use it in GitHub Desktop.
Save polevaultweb/eb6295b38c540dafec31 to your computer and use it in GitHub Desktop.
<?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;
}
@Asshad
Copy link

Asshad commented Nov 14, 2017

Hi. Is this only applicable for Pro version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment