Author: Stasyuk Eugene 41 Tags: , , 03.04.2024

WP_Query class is one of the WordPress tools that helps to display posts according to the required parameters: categories, sorting, date range, etc. The list of parameters is pretty decent. You can read more about them in the documentation here: https://developer.wordpress.org/reference/classes/wp_query/ . Some parameters are quite extensive and sometimes it’s much easier to understand them when you have ready examples. And I have just such an example.

Site posts are linked to events that have a date. In the admin on the post edit page I have displayed an arbitrary field with a date selection. The arbitrary field is called date

date field

On the archive page we have a form with a filter with two inputs specifying the date range we are interested in:

date range

Code in full

This means that we will take the date values from the GET parameters of our query. The full code with parameters for WP_Query will look like this:

$args = [
    'posts_per_page' => 12,
];

$date = [
    'date_from' => !empty($_GET['date_from']) ? $_GET['date_from'] : false,
    'date_to' => !empty($_GET['date_to']) ? $_GET['date_to'] : false,
];

//set the date format
foreach ($date as $name => $value):
    if (!$value) continue;

    $date_val = date_create($value);

    $date[$name] = date_format($date_val, 'Ymd');
endforeach;

//set meta query
if ($date['date_from'] || $date['date_to']):

    if ($date['date_from'] && !$date['date_to']) {
        $args['meta_query'][] = [
            'key'     => 'date',
            'value'   => $date['date_from'],
            'compare' => '>=',
            'type'    => 'DATE'
        ];
    }

    if (!$date['date_from'] && $date['date_to']) {
        $args['meta_query'][] = [
            'key'     => 'date',
            'value'   => $date['date_to'],
            'compare' => '<=',
            'type'    => 'DATE'
        ];
    }

    if ($date['date_to'] && $date['date_from'] ) {
        $args['meta_query'][] = [
            'key'     => 'date',
            'value'   => [
                $date['date_from'],
                $date['date_to']
            ],
            'compare' => 'BETWEEN',
            'type'    => 'DATE'
        ];
    }

endif;

$query = new WP_Query($args);

We will set the date range in WP_Query in the meta_query parameter.

Create an array with parameters:

$args = [
    'posts_per_page' => 12,
];

Create an array in which we will put the values of the date range. Depending on the availability of values, we will set different meta_query parameters :

$date = [
    'date_from' => !empty($_GET['date_from']) ? $_GET['date_from'] : false,
    'date_to' => !empty($_GET['date_to']) ? $_GET['date_to'] : false,
];

Next, we set the date format we need. We will do it using a loop:

foreach ($date as $name => $value):
    if (!$value) continue;

    $date_val = date_create($value);

    $date[$name] = date_format($date_val, 'Ymd');
endforeach;

Date range – parameters in meta_query

Next, let’s go directly to the meta_query parameter. It can have one or more arrays with the following keys:

  • key – (string) name of an arbitrary field to be filtered by;
  • type – (string) field type. Possible options ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’. Default ‘CHAR’.;
  • value – (string|array) The value of our arbitrary field. It can be an array only if the compare key has a value of ‘IN’, ‘NOT IN’, ‘BETWEEN’ or ‘NOT BETWEEN’.
  • compare – (string) Operator to check. Possible values: ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘EXISTS’ и ‘NOT EXISTS’. Default value – ‘=’.

If we have a known start date but an unknown end date:

if ($date['date_from'] && !$date['date_to']) {
        $args['meta_query'][] = [
            'key'     => 'date',
            'value'   => $date['date_from'],
            'compare' => '>=',
            'type'    => 'DATE'
        ];
    }

If we have a known end date but an unknown start date:

if (!$date['date_from'] && $date['date_to']) {
        $args['meta_query'][] = [
            'key'     => 'date',
            'value'   => $date['date_to'],
            'compare' => '<=',
            'type'    => 'DATE'
        ];
    }

When both dates are known. Note that in value we will add an array with values that will be compared with each other:

if ($date['date_to'] && $date['date_from'] ) {
        $args['meta_query'][] = [
            'key'     => 'date',
            'value'   => [
                $date['date_from'],
                $date['date_to']
            ],
            'compare' => 'BETWEEN',
            'type'    => 'DATE'
        ];
    }

Finally, we put the $args variable into the WP_Quey class and use a loop to output our posts. You can see how to use the loop here

$query = new WP_Query($args);

Back to home page

Other articles

Wp Favs – plugin manager for WordPress

Wp Favs – plugin manager for WordPress

Wp Favs – plugin manager for WordPress

When you create WordPress templates on a regular basis, you come across one procedure that takes up some of your time – downloading and activating plugins. The WP Favs plugin solves this problem quite successfully. You simply create a list of plugins that you use regularly and then bulk upload them to your site. The […]

Popup window on the site (modal window) pop-up window

Popup window on the site (modal window)

Popup window on the site (modal window)

When I was just learning the basics of development, I used to make a popup window manually. Yes, yes – instead of finding some ready-made solution, I did this thankless task 🤪. It seemed to me that there was nothing particularly complicated about it. But, only after some time of working on this issue, I […]