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

Position sticky doesn’t work position: sticky

Position sticky doesn’t work

Position sticky doesn’t work

Position sticky doesn’t work – to my surprise this is a fairly common request that I myself have encountered in my time. Sticky is a pretty simple and versatile solution for placing sticky blocks on a page. At the very least, it doesn’t require you to do a decent amount of javascript code, which did […]

How to import a large MySQL database into OpenServer

How to import a large MySQL database into OpenServer

How to import a large MySQL database into OpenServer

Perhaps everyone is used to importing a database using phpMyAdmin. But this platform has a limit on the weight of the file that can be uploaded. So if the database dump exceeds this quota, you can’t do it through phpMyAdmin. Today I’m going to show an alternative way to load the database – through the […]