Skip to content

Instantly share code, notes, and snippets.

@dimadin
Last active December 30, 2015 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimadin/7863477 to your computer and use it in GitHub Desktop.
Save dimadin/7863477 to your computer and use it in GitHub Desktop.
Used in combination with (heavily) modified Simple Colorbox plugin.
<?php
if ( class_exists( 'Simple_Colorbox' ) ) :
/**
* Conditional Simple Colorbox loader.
*
* Enqueue Colorbox files only when needed on page to improve
* performance by avoiding unnecessary external requests and
* inline content.
*
* If Colorbox is needed only when galleries are used,
* remove expensive search through post's content.
*/
class Conditional_Simple_Colorbox extends Simple_Colorbox {
/**
* Adds all the methods to appropriate hooks or shortcodes.
*/
public function __construct() {
// Load parent
parent::__construct();
// Remove action hooks
remove_action( 'wp_enqueue_scripts', array( $this, 'external_css' ) );
remove_action( 'wp_enqueue_scripts', array( $this, 'external_scripts' ) );
// Add filter
add_filter( 'the_content', array( $this, 'the_content' ) );
add_filter( 'post_gallery', array( $this, 'post_gallery' ) );
}
/**
* Load Colorbox when there is a link to image in post's content.
*
* @todo Improve REGEX to find only links without img tags.
*/
public function the_content( $content ) {
if ( ! did_action( 'md_loaded_colorbox' ) ) {
$num = preg_match_all( '#(http://[^\s]+(?=\.(jpe?g|png|gif)))#i', $content, $matches );
if ( $num > 0 ) {
$this->external_css();
$this->external_scripts();
do_action( 'md_loaded_colorbox' );
}
}
return $content;
}
/**
* Load Colorbox on gallery shortcode.
*/
public function post_gallery( $output ) {
if ( ! did_action( 'md_loaded_colorbox' ) ) {
$this->external_css();
$this->external_scripts();
do_action( 'md_loaded_colorbox' );
}
return $output;
}
}
/**
* Initialize Colorbox.
*
* Load class when all plugins are loaded
* so that other plugins can overwrite it.
*/
function conditional_simple_colorbox_instantiate() {
global $simple_colorbox;
$simple_colorbox = new Conditional_Simple_Colorbox();
}
add_action( 'plugins_loaded', 'conditional_simple_colorbox_instantiate', 15 );
/**
* Deinitialize a Simple Colorbox plugin.
*
* Unload class when all plugins are loaded
* but before class in instantiated.
*/
function conditional_simple_colorbox_deinstantiate() {
remove_action( 'plugins_loaded', 'simple_colorbox_instantiate', 15 );
}
add_action( 'plugins_loaded', 'conditional_simple_colorbox_deinstantiate', 14 );
endif; // class_exists( 'Simple_Colorbox' )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment