I’ve written a shortcode for fetching the most viewed posts in the past week. I use a filter as the following in my shortcode’s function:

function filter_where($where = '') {
    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-7 days')) . "'";
    return $where;
add_filter('posts_where', 'filter_where');

// new WP_Query and stuff goes here

remove_filter('posts_where', 'filter_where');

I used this in a PHP widget before, and it worked fine. Now, there is a problem with it : It affects every other query on the page, including other shortcodes.

I’m resetting the post data after the query has finished, so i don’t know what’s wrong, since it used to work (and still does work) in a PHP widget. Just doesn’t work in shortcode.

Am i missing something?

Read more here: How to filter a query by date in a shortcode?


If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Wordpress related questions and answers: