CreateIT
CreateIT
BLOG

WP_Query – sorting by date

Query Blog

WP_Query – sorting by date

SHARE

CHALLENGE:
Sort posts using a custom date field
SOLUTION:
Use meta_query parameter

The WordPress CMS functionality provides an option to create custom post types. We often want to display items in particular order, mostly DESC (newest at the top).

Order using default post_date (published date)

$args = [
            'post_type'   => 'my_custom_post_type',
            'posts_per_page' => -1,
            'orderby' => 'date',
            'order'   => 'DESC',
        ];
$postslist = get_posts( $args );

But what if we want to store a date in a custom field ( Advanced Custom Fields plugin )? Having a custom field defined as a date allows us to have better control over data. We can also fill in the date value from the future, which is not really possible when using published_date from WordPress. In this example, the custom field name is: ‘custom_date’ and the example value will be: November 30, 2020, stored in the database as the following string: 20201130 . To render a list from newest to oldest :

 $args = [
            'post_type'   => 'my_custom_post_type',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'order'=>'DESC',
            'orderby'=>'meta_value_num',
            'meta_key'=>'custom_date',
        ];
$postslist = get_posts( $args );

WordPress meta_query is a very powerful tool, we can adjust query logic to our needs. Let’s try now: display all items with a custom date in the future.

// DB format for custom_date : 20201130
        $today = date('Ymd');

        $args = [
            'post_type'   => 'my_custom_post_type',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'order'=>'DESC',
            'orderby'=>'meta_value_num',
            'meta_key'=>'custom_date',
            'meta_query' => array(
                'relation' => 'AND',
                array(
                    'key'     => 'custom_date',
                    'value'   =>  $today,
                    'compare' => '>'
                ),
                array(
                    'key' => 'custom_date',
                    'compare' => 'EXISTS',
                ),
            ),
        ];
$postslist = get_posts( $args );

What about showing all items from the last 4 weeks, starting today? We can use this meta_query:

  $today = date('Ymd');
        $date_4_weeks_ago = strtotime($today.'- 4 weeks');
        $date_4_weeks_ago_ymd_val = date('Ymd',$date_4_weeks_ago);

        $args = [
            'post_type'   => 'my_custom_post_type',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'meta_query' => array(
                'relation' => 'AND',
                array(
                    'key'     => 'custom_date',
                    'value'   =>  $today,
                    'compare' => '<='
                ),
                array(
                    'key'     => 'custom_date',
                    'value'   =>  $date_4_weeks_ago_ymd_val,
                    'compare' => '>='
                ),
            ),
            'order'=>'DESC',
            'orderby'=>'meta_value_num',
            'meta_key'=>'custom_date',
        ];
$postslist = get_posts( $args );

 

Summary

Wp-query – a built in WordPress functionality – provides an option to sort elements using post_date. We can even use a custom field with a custom format (a date defined as string value Ymd) and order elements according to our needs. Using a custom field for a date is more flexible than WordPress publish_date and allows to have items with dates in the future.

___

About the article Author:

Maciej Brzeziński

Techleader of createIT, working in the IT sector for over 14 years. Innovator, author, and owner of an e-shop that he has been continuously developing for over 10 years. Currently, with his team of over 20 developers, he supervises all kinds of e-commerce projects of varied structure, characteristics, and size: from simple on-line shops for retail clients to advanced B2B platforms with support of multiple shopping carts, multiple languages, and integration with external systems. His work also involves modifying and expanding the existing platforms with millions of products in their databases, platforms that support variable pricing (several variants of the same product), dropshipping modules, integration with storage systems, integration with courier delivery services, and the last but not least, the optimization of scripts. By participating in a multitude of projects, he had the opportunity to “test out” all kinds of platforms (open-source, SaaS – Cloud-Hosted eCommerce Platforms) and dedicated platforms.

About us:

Hi, we are createIT!

As a passionate group of professionals with a love for Web and mobile technologies, we have been successfully serving our clients for the past 15 years. Through these years we have continuously striven to create the best IT solutions our clients seek.

Our 70+ developer team creates cutting-edge complex B2B and B2C web systems and apps as well as delivers top-notch direct outsourcing services.

We work in multiple frameworks but we hold special feelings and are experts in PHP (Symfony, OXID, WordPress), JavaScript (React, AngularJS), Flutter and Blockchain. We do enjoy working in the scalable cloud environment like AWS.

We are located in Warsaw, Poland, in the heart of Europe. Concentrated on delivering durable web solutions of high integrity, we do not always try to be the cheapest. However, thanks to our location you will be surprised how reasonable our prices are.

Fluent in English we offer services worldwide. Among others, in countries such as the U.S.A., Great Britain, Germany, Australia, Sweden and Poland.

Popular News

Need help?

  • Looking for support from experienced programmers?

  • Need to fix a bug in the code?

  • Want to customize your webste/application?

ADD COMMENT

Your email address will not be published. Required fields are marked *

createIT Contact