I have a post where filter set up for a CPT archive page. Which works great but i have other WP_Query objects in the sidebar that dont work because the post_where filter is effecting those Objects too. How can i get the filter to only work on the main page and not the sidebar?

add_filter('posts_where', 'Where_Events', 10, 1);
function Where_Events($where)
    global $wpdb;
    $current_date = new DateTime('now');
    $current_month = $current_date->format('m');
    $current_year = $current_date->format('Y');

$query_month = get_query_var( 'eventMonth', $current_month );
$query_year = get_query_var( 'eventYear', $current_year );
$query_day = '01';
$query_date = $query_year .'-'. $query_month . '-' . $query_day;

// check date where function
//default return current month
if (! is_admin() && (is_post_type_archive('gnl_events') && is_main_query())) {
    $where .= ' AND MONTH(events_occurence) = MONTH("'.$query_date.'")';
    $where .= ' AND YEAR(events_occurence) = YEAR("'.$query_date.'")';
return $where;


  • I got it to work by removing the filter before the new WP_Query in the sidebar.. and readded the filter after, but not sure if that is the best/only way.
    – Joe
    Jun 19, 2019 at 16:50

1 Answer 1


The second parameter here would be useful in targeting the appropriate context.

add_filter( 'posts_where', 'Where_Events', 10, 2  );
function Where_Events( $where, $wp_query ) { }

The global $wp_query would be able to tell you whether the query was for the main query by checking $wp_query->is_main_query().

  • 1
    that worked... thank you!
    – Joe
    Jun 22, 2019 at 12:42

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.