Skip to content

Instantly share code, notes, and snippets.

@ronalfy
Created July 11, 2015 16:08
Show Gist options
  • Save ronalfy/a6f46a89459e5ac93080 to your computer and use it in GitHub Desktop.
Save ronalfy/a6f46a89459e5ac93080 to your computer and use it in GitHub Desktop.
WordPress - Limit Actions
<?php
class I_Am_Evil {
private $times = 0;
private $callbacks = array();
private $accepted_args = array();
public function __construct() {
}
public function load() {
global $wp_filter;
if ( isset( $wp_filter[ 'my_test_action' ] ) ) {
foreach( $wp_filter[ 'my_test_action' ] as $priority => &$registered_actions ) {
foreach( $registered_actions as $actionkey => &$callback_args ) {
$this->callbacks[] = $callback_args[ 'function' ];
$this->accepted_args[] = $callback_args[ 'accepted_args' ];
$callback_args[ 'function' ] = array( $this, 'callback' );
}
}
}
do_action( 'my_test_action', 'test1', 'test2' ); //Assuming pass two strings
}
public function callback( $arg = '' ) {
echo 'hijacked callback run' . '<br />';
//From do_action
$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
$args[] =& $arg[0];
else
$args[] = $arg;
for ( $a = 2, $num = func_num_args(); $a < $num; $a++ )
$args[] = func_get_arg($a);
//LIMIT TO 5 TIMES
if ( $this->times > 4 ) {
echo 'third-party callback skipped' . '<br />';
} else {
//Modified from do_action
call_user_func_array( $this->callbacks[ $this->times ], array_slice($args, 0, (int) $this->accepted_args[ $this->times ] ) );
}
//Increment times
$this->times++;
}
}
class I_Am_Not_Evil {
public function __construct() {
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 1, 2 );
add_action( 'my_test_action', array( $this, 'another_not_evil_callback' ), 1, 2 ); //testing multiple with same priority
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 2, 2 );
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 3, 2 );
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 4, 2 );
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 5, 2 );
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 6, 2 );
add_action( 'my_test_action', array( $this, 'not_evil_callback' ), 7, 2 );
}
public function not_evil_callback( $arg1 = '', $arg2 = '' ) {
echo 'original callback reached' . '<br />';
}
public function another_not_evil_callback( $arg1 = '', $arg2 = '' ) {
echo 'original callback reached' . '<br />';
}
}
//Register Not Evil Class
new I_Am_Not_Evil();
//Register Evil Class
$evil = new I_Am_Evil();
$evil->load();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment