Skip to content

Instantly share code, notes, and snippets.

@jeremyclark13
Created May 10, 2013 14:40
Show Gist options
  • Select an option

  • Save jeremyclark13/5554820 to your computer and use it in GitHub Desktop.

Select an option

Save jeremyclark13/5554820 to your computer and use it in GitHub Desktop.
Calling a filter with an additional parameter.
<?php
/**
* Stores a value and calls any existing function with this value.
*/
class Filter_Storage
{
/**
* Filled by __construct(). Used by __call().
*
* @type mixed Any type you need.
*/
protected $values;
/**
* Stores the values for later use.
*
* @param mixed $values
* @return void
*/
public function __construct( $values )
{
$this->values = $values;
}
/**
* Catches all function calls except __construct().
*
* Be aware: Even if the function is called with just one string as an
* argument it will be sent as an array.
*
* @param string $callback Function name
* @param array $arguments
* @return mixed
*/
public function __call( $callback, $arguments )
{
if ( is_callable( $callback ) )
{
return call_user_func( $callback, $arguments, $this->values );
}
// Wrong function called.
throw new InvalidArgumentException(
sprintf(
'File: %1$s<br>
Line %2$d<br>
There is no function %3$s',
__FILE__,
__LINE__,
$name
)
);
}
}
function filter_where( $args, $time ) {
// posts in the last 30 days
$where = $args[0];
$where .= " AND post_date > '" . date('Y-m-d', strtotime("-$time[0] days")) . "'";
return $where;
}
//Call the filter like this
//This will limit to 30 days
$time_limit = new Filter_Storage(
array( '30' )
);
//Add the filter to run for the next query
add_filter(
'posts_where',
// Object instance and called function.
array( $time_limit, 'filter_where' )
);
//Run the WP_Query
$query = new WP_Query();
//Remove the filter
remove_filter(
'posts_where',
// Object instance and called function.
array( $time_limit, 'filter_where' )
);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment