Skip to content

Instantly share code, notes, and snippets.

@dipakcg
Last active October 28, 2020 07:13
Show Gist options
  • Save dipakcg/d831856a7e87044ab9961e513b6be4a9 to your computer and use it in GitHub Desktop.
Save dipakcg/d831856a7e87044ab9961e513b6be4a9 to your computer and use it in GitHub Desktop.
WordPress : Load any third-party script locally
<?php
//Define uploads directory to store cached/downloaded scripts
$wp_upload_dir = wp_upload_dir();
define( 'LOCAL_SCRIPTS_UPDLOAD_DIR', $wp_upload_dir['basedir'] . '/dcg-locally-stored-scripts' );
define( 'LOCAL_SCRIPTS_UPDLOAD_URL', $wp_upload_dir['baseurl'] . '/dcg-locally-stored-scripts' );
// Create a scheduled event (if it doesn't exist)
function dcg_cron_activate() {
if( !wp_next_scheduled( 'dcg-get-external-scripts-cron' ) ) {
wp_schedule_event( time(), 'daily', 'dcg-get-external-scripts-cron' );
}
}
// Activate cron when WordPress loads
add_action( 'wp', 'dcg_cron_activate' );
// Hook the function into scheduled event
add_action( 'dcg-get-external-scripts-cron', 'dcg_file_to_store' );
// Unschedule cron upon plugin deactivation
function dcg_cron_deactivate() {
// Find out the last cron event was scheduled
$timestamp = wp_next_scheduled ( 'dcg-get-external-scripts-cron' );
// Unschedule previous event if any
wp_unschedule_event ( $timestamp, 'dcg-get-external-scripts-cron' );
}
register_deactivation_hook ( __FILE__, 'dcg_cron_deactivate' );
// Initiate the function to store file locally from remote URL
function dcg_file_to_store() {
// clutch.co widget
dcg_download_file( 'https://static1.clutch.co/api/widget.js', LOCAL_SCRIPTS_UPDLOAD_DIR . '/dcg_clutch_widget_local.js' );
// lead forensic tracking
dcg_download_file( 'https://secure.tula9mari.com/js/151014.js', LOCAL_SCRIPTS_UPDLOAD_DIR . '/dcg_lead_forensic_local.js' );
}
add_action( 'init', 'dcg_file_to_store' );
// Function that retrieve file from remote server to local
function dcg_download_file( $url, $filename ) {
if ( !file_exists( LOCAL_SCRIPTS_UPDLOAD_DIR ) && !is_dir( LOCAL_SCRIPTS_UPDLOAD_DIR ) ) {
mkdir( LOCAL_SCRIPTS_UPDLOAD_DIR );
}
$file = fopen ( $url, "rb" );
if ( !$file ) return false;
else {
$fc = fopen( $filename, "wb" );
while ( !feof ( $file ) ) {
$line = fread ( $file, 1028 );
fwrite( $fc, $line );
}
fclose( $fc );
return true;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment