Using dynamic conditions in ‘posts_where’ filter

The question:

I have the following code which gives be posts that are published in the last 100 days

function smbd_cats_by_days ($where = '') {

    $where .= " AND post_date < '" . date('y-m-d', strtotime("-100 days")) . "'";
    return $where;

add_filter('posts_where', 'smbd_cats_by_days');

It is working fine. But now I want to make this function generic. (ie) I want the number of days to be stored in a variable instead of hard coding it as 100.

How to do that?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I was afraid you wanted that one. You can’t really do that. Follow the link for some workarounds. You could also set a variable or a constant in functions.php, or create a theme option for this. Then use that in your function.

function smbd_cats_by_days ($where = '') {
    // global $days_limit; // if a variable
    // $days_limit = DAYS_LIMIT; // if a constant
    // $days_limit = get_option('days_limit',100);
    // you have to uncomment one of the above, 
    // depending on your choice of mechanisms
    $where .= " AND post_date < '" . date('y-m-d', strtotime("-{$days_limit} days")) . "'";
    return $where;

add_filter('posts_where', 'smbd_cats_by_days');

Method 2

You could use an anonymous function, as per this blog post, which utilises the creation of an on-the-fly function for the posts_where filter:

$options = array(
    'max_post_age' => '30 days'

$age_filter = function ($where = '') use ( $options ) {
    $where .= " AND post_date > '" . date( 'Y-m-d', strtotime( '-' . $options[ 'max_post_age' ] ) ) . "'";
    return $where;

add_filter('posts_where', $age_filter);
$query = new WP_Query($args);
remove_filter('posts_where', $age_filter);

The author does go the extra step of implementing this in a single expression, but utilising the anonymous function should work perfectly for most circumstances.

It’s also worth noting that WordPress 3.7 will have a new set of very handy date parameters added to WP_Query.

EDIT: As I discovered myself last night, the Lambda function (i.e. function ($where = '') use ( $options )) is only available in PHP 5.3+.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment