Author: Stasyuk Eugene 200 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

Simple star rating stars

Simple star rating

Simple star rating

In this article, I will show you how to make the visual part of the star rating. Namely: Finished option: Markup As a markup, we have a container block with the .rate class inside which I have placed 5 links. I used a font as a star. But most likely in practice you will have […]

How to Translate a WordPress Theme to Another Language перевод

How to Translate a WordPress Theme to Another Language

How to Translate a WordPress Theme to Another Language

While working on creating a WordPress theme, we often come across such inscriptions as “upload more, author, tags”, etc. For example, as in my blog: It’s good when the site is in one language. Then you don’t really need to do anything with them. But what to do when the site is multilingual. If the […]