3

I have just started with WordPress Development, and found following block of code online (in some tutorial)

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

add_filter( 'posts_where', 'filter_where' );

$args = array(
    'posts_per_page' => -1,
);
$the_query = new WP_Query($args);

remove_filter( 'posts_where', 'filter_where' );

I am not able to understand why add_filter and remove_filter are called before and after WP_Query? In what scenario we need to use above kind of pattern?

1 Answer 1

4

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;
}
3
  • first of all, thanks for quick reply. I am quite new to WordPress, can you please explain in bit detail
    – I-M-JM
    Apr 27, 2013 at 6:33
  • @I-M-JM Better now?
    – fuxia
    Apr 27, 2013 at 6:36
  • Hmmm, it's much better now.Also liked your suggestion to remove filter in function body itself.
    – I-M-JM
    Apr 27, 2013 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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