Last active
May 19, 2023 09:01
-
-
Save pritdeveloper/db1331c01d5cfbd895775e297a15389e to your computer and use it in GitHub Desktop.
mu-plugin for wordpress
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: Singh MU Plugin | |
* Description: This plugin is used to provide all helper functions and a special functionality to use the original domain url for attachments | |
*/ | |
if( file_exists( __DIR__ . "/vendor/autoload.php" ) ) { | |
require_once __DIR__ . "/vendor/autoload.php"; | |
} | |
// helper functions copy from https://gist.github.com/pritdeveloper/6c1b3ba4770731fc48fb6fbd329b1430/raw | |
/** | |
* This is used to change all the URLs to use the original domain url | |
* instead of the cloned server url for all the attachments | |
*/ | |
add_filter( 'wp_get_attachment_url', function( $url ) { | |
// the urls should be without https:// and trailing slash, eg, example.com | |
$new_domain = ''; | |
$old_domain = ''; | |
if( $new_domain && $old_domain && function_exists( 'curl_init' ) ) { | |
$urls_file = '.mu_singh_urls__'; | |
$wp_upload_dir = wp_upload_dir(); | |
$urls_file_path = untrailingslashit( $wp_upload_dir[ 'basedir' ] ) . "/{$urls_file}"; | |
if( !file_exists( $urls_file_path ) ) { | |
@touch( $urls_file_path ); | |
} | |
$f_contents = file_get_contents( $urls_file_path ); | |
$urls = maybe_unserialize( $f_contents ); | |
if( !is_array( $urls ) ) { | |
$urls = array(); | |
} | |
$md5 = md5( $url ); | |
if( isset( $urls[ $md5 ] ) ) return $urls[ $md5 ]; | |
$ch = curl_init( $url ); | |
curl_setopt( $ch, CURLOPT_NOBODY, true ); | |
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); | |
curl_setopt( $ch, CURLOPT_TIMEOUT, 5 ); | |
curl_exec( $ch ); | |
$code = curl_getinfo( $ch, CURLINFO_HTTP_CODE ); | |
curl_close( $ch ); | |
if( 200 != $code ) { | |
$url = str_replace( untrailingslashit( $new_domain ), untrailingslashit( $old_domain ), $url ); | |
} | |
$urls[ $md5 ] = $url; | |
// update_option( $option_key, $option ); | |
$h = fopen( $urls_file_path, 'w' ); | |
fwrite( $h, maybe_serialize( $urls ) ); | |
fclose( $h ); | |
} | |
return $url; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment