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?

  • 1
    How do you want to set the variable? Not technically, programmer-y "how", but human "how"? Is this a theme option? Do you want to pass a parameter when you add the filter? Set a constant? What?
    – s_ha_dum
    Commented Dec 8, 2012 at 16:40
  • I want to pass it as a parameter when I add the filter.
    – Sudar
    Commented Dec 8, 2012 at 16:41
  • Duplicate of Custom time range for the posts_where filter
    – Milo
    Commented Oct 17, 2013 at 18:06

2 Answers 2


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');



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+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.