add_filter and remove_filter added before and after wp_query

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?

Related posts

Leave a Reply

1 comment

  1. 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;
    }