Programmatically Search WordPress Posts By Date Range

[ad_1]

TL;DR: The code shared in this post shows how you can modify the query that runs on the All Posts page so you can limit how you search posts to a specified date range.

It’s been a little while since I last wrote about using the post_where filter for modifying the search query that runs on a given page, such as the All Posts area of WordPress. But given the fact that there are a variety of uses for retrieving posts – and custom post types – in different ways, there’s a variety of ways to use this single filter.

Search Posts By Date Range

In order to search posts by date range, here’s what needs to happen:

  1. Register a callback with the posts_where filter,
  2. Make sure the function accepts the string for where and the instance of WP_Query that’s running on the page
  3. Get todays date and time and the date and time for four weeks ago
  4. Prepend the where clause to constrain the results to the date
  5. return the updated query.
<?php
add_filter( 
  'posts_where',
  function ( string $where, WP_Query $query ) : string {
    global $wpdb;

    $todays_date   = gmdate( 'Y-m-d H:i:s', strtotime( 'now' ) );
    $four_weeks_ago = gmdate( 'Y-m-d H:i:s', strtotime( '-4 weeks' ) );

    $prepend = $wpdb->prepare(
      " AND {$wpdb->posts}.post_date > %s",
      $four_weeks_ago
    );

    $prepend .= $wpdb->prepare(
      " AND {$wpdb->posts}.post_date < %s",
      $todays_date
    );

    return $prepend . $where;
  }, 101, 2
);

The result of this function is a modified query that restricts the posts that are returned by the specified date and time. Namely, four weeks ago up to the hour, minute, and second.

You can change this by updating the -4 weeks string passed to the strtotime function (but I recommend reviewing the PHP manual page linked below to understand how this function works with language like this).

References

[ad_2]

Source link