Skip to content

Instantly share code, notes, and snippets.

@ginsterbusch
Created February 5, 2019 04:09
Show Gist options
  • Save ginsterbusch/b9017bf7e7e694380ae28b64a51dd97e to your computer and use it in GitHub Desktop.
Save ginsterbusch/b9017bf7e7e694380ae28b64a51dd97e to your computer and use it in GitHub Desktop.
Copy + paste of the assets preloader from the soon-to-be released next version of UI Leaflet Integration plugin (https://github.com/ginsterbusch/ui-leaflet-integration ).
<?php
/**
* @author Fabian Wolf (https://wp-devil.de)
* @license GNU GPL v2 or later
*/
class AssetsPreloaderExample {
function __construct() {
add_action( 'wp', array( $this, 'preload_assets' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'init_assets' ) );
}
/**
* Test if current post contains one of "our" shortcodes and if so, load assets
*
* Struct:
* - Check in preload_assets if shortcodes are being used
* - if so, use add_action( 'wp_enqueue_scripts + init AND load_assets
* - done!
*/
function preload_assets() {
$post_id = parent::get_post_id();
//new __debug( $post_id, __METHOD__ );
if( empty( $post_id ) ) {
global $post;
if( !empty( $post ) && isset( $post->ID) ) {
$post_id = $post->ID;
}
}
//new __debug( $post_id, __METHOD__ );
if( !empty( $post_id ) ) {
$current_post = get_post( $post_id );
$arrTargets = array();
//new __debug( $current_post, 'current_post - ' . __METHOD__ );
//$current_post->post_content
$post_meta = get_metadata( 'post', $post_id );
//new __debug( $post_meta, 'post meta - ' . __METHOD__ );
if( !empty( $post_meta ) ) {
$arrTargets = $post_meta;
}
$arrTargets['post_content'] = $current_post->post_content;
$arrMethods = $this->_get_methods_by( 'prefix', 'shortcode_' );
//new __debug( $arrTargets, 'targets - ' . __METHOD__ );
if( !empty( $arrMethods ) ) {
foreach( $arrMethods as $strMethod ) { // avoid clashes with the sks helper shortcodes
$strShortcode = str_replace( 'shortcode_', '', $strMethod );
foreach( $arrTargets as $single_target ) { // cycle through possible DIFFERENT strings (what we search for is not necessarly contained in the regular post_content)
if( is_array( $single_target ) ) {
$strContentTarget = reset( $single_target );
} else {
$strContentTarget = $single_target;
}
if( strpos( $strContentTarget, '[' . $strShortcode ) !== false ) {
$arrDetectedShortcode[ $strShortcode ] = 1;
}
}
}
}
}
//new __debug( $arrDetectedShortcode, 'detected shortcodes - ' . __METHOD__ );
if( !empty( $arrDetectedShortcode ) ) { // load assets
add_action( 'wp_enqueue_scripts', array( $this, 'init_assets' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) );
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment