Skip to content
Headless Platform
GitHubDiscordYouTube

Using Date filtering

Smart Search

Date filtering

date_query

Filter based on date.

Parameters

array $wp_date_queries: An array of date queries. See WP_Date_Query. Each query can contain the following keys:

  • relation (optional): The logical relation between queries (AND or OR). Default is AND.
  • year
  • month
  • day
  • hour (optional)
  • minute (optional)
  • second (optional)
  • before (optional): A date or array specifying the upper bound of the date range.
  • after (optional): A date or array specifying the lower bound of the date range.
  • inclusive (optional): A boolean indicating whether the date range is inclusive. Default is true.
  • comparison (optional): Accepts ’=’, ’!=’, ’>’, ’>=’, ’<’, ’<=‘. Default ’=‘. Currently we do not support ‘IN’, ‘BETWEEN’, ‘NOT IN’ and ‘NOT BETWEEN’.

Description

This filter prevents posts and pages outside the date ranges from being returned. WPE Smart Search respects these date filters.

Examples

You would want to only show posts from 1/1/2021 OR before 2024-01-13 inclusive OR before 2023-12-12 at exactly 12:12:12.

The following arrays can be built with this WP_Date_Query Generator.

add_action( 'pre_get_posts', function( $query ) {
	// Ensure this only modifies the main query on the front-end.
	if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
		// Set up date query arguments.
		$date_query_args = array(
			'relation' => 'OR',
			array(
				'year'    => 2021,
				'month'   => 1,
				'day'     => 1,
				'compare' => '=',
			),
			array(
				'before'    => '2024-01-13',
				'inclusive' => true,
			),
			array(
				'year'    => 2023,
				'month'   => 12,
				'day'     => 12,
				'hour'    => 12,
				'minute'  => 12,
				'second'  => 12,
				'compare' => '<',
			),
		);
		// Apply the date query to the main query.
		$query->set( 'date_query', $date_query_args );
	}
});