Skip to content

Instantly share code, notes, and snippets.

@klihelp
Created March 12, 2014 12:48
Show Gist options
  • Save klihelp/9506254 to your computer and use it in GitHub Desktop.
Save klihelp/9506254 to your computer and use it in GitHub Desktop.
WordPress Plugin Isolation helper
<?php
/**
* WordPress Plugin Isolation helper
* This helps your plugin/theme to have isolated webpages, keeping only your organized prefixed hooks.
* @package Hashtagg
* @subpackage Base
* @author Klipolis
* @copyright 2014 Klipolis
* @since 0.1.0
* @version 0.1.0
* @access public
*
*
* Example call: filter_this_hook('wp_head', 'MY_')
*/
/**
* filter_this_hook()
*
* @var string $hook_name
* @var string $prefixes Can be array too
* @var bool $update_that_hook return
* @return array Return the array of the matched hooks
*/
public function filter_this_hook( $hook_name = '', $prefixes = 'YOUR_', $update_that_hook = true ) {
global $wp_filter;
if ( ! isset($wp_filter[$hook_name]) ) {
return false;
}
$hook = $wp_filter[$hook_name];
foreach ( $hook as $priority => $functions ) {
foreach ( $functions as $key => $function ) {
$callback = $function['function'];
if ( is_string( $callback ) ) {
// string
if ( validate_callback_text( $callback, $prefixes) ) {
$keep_key = $key;
}
// } elseif ( is_a( $callback, 'Closure' ) ) {
//clusure
// $closure = new ReflectionFunction( $callback );
// if ( validate_callback_text( $callback) ) {
// $keep_callbacks[$priority][$key] = '';
// }
} elseif ( is_string( $callback[0] ) ) {
// static method call
if ( validate_callback_text( $callback[0], $prefixes ) ) {
$keep_key = $key;
}
} elseif ( is_object( $callback[0] ) ) {
// object
if ( validate_callback_text( get_class($callback[0]), $prefixes ) ) {
$keep_key = $key;
}
}
if ( isset($keep_key) ) {
$keep_callbacks[$priority][$keep_key] = $function;
unset($keep_key);
}
}
}
if ( isset($keep_callbacks) && is_array($keep_callbacks) ) {
if ( $update_that_hook ) {
$wp_filter[$hook_name] = $keep_callbacks;
}
return $keep_callbacks;
}
return false;
}
/**
* validate_callback_text()
*
* @var string $callback_text
* @var array $prefixes Can be string if only one prefix
* @var bool $keep_wp_hooks
* @return bool
*/
public function validate_callback_text( $callback_text, $prefixes = 'hg_' ,$keep_wp_hooks = true ) {
if ( ! $callback_text ) {
return false;
}
if ( ! is_array($prefixes) ) {
$prefixes = (array) $prefixes;
}
if ( $keep_wp_hooks ) {
$prefixes[] = 'WP_';
}
$callback_text = strtolower($callback_text);
foreach ($prefixes as $key => $prefix) {
$prefix = strtolower($prefix);
if ( false !== stripos($callback_text, $prefix) || ( $keep_wp_hooks && false !== stripos( $callback_text, 'wp_') ) ) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment