Take the 2-minute tour ×

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?

share|improve this question
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 Dec 8 '12 at 16:40
I want to pass it as a parameter when I add the filter. –  Sudar Dec 8 '12 at 16:41
Duplicate of Custom time range for the posts_where filter –  Milo Oct 17 '13 at 18:06
add comment

2 Answers

up vote 1 down vote accepted

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


share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


