add_filter and remove_filter added before and after wp_query

This was done to restrict the effect of those filters to this one query between both calls.

There are probably other instances of WP_Query during page load, and you don’t want to change their results.

Imagine what happens when you do not remove the filter: All later new WP_Query(); calls would be restricted to a certain date period. All posts from an author, all pages, custom post types … that would really hurt.

You don’t even need the second call, you can remove the filter from the first callback:

function filter_where( $where="" ) 
{
    remove_filter( current_filter(), __FUNCTION__ );
    // posts in the last 30 days
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
    return $where;
}

Leave a Comment