Get a free advice now!

    Pick the topic

    Developer OutsourcingWeb developingApp developingDigital MarketingeCommerce systemseEntertainment systems

    Thank you for your message. It has been sent.

    Tags

    WP_Query – order by date, different sorting options

    WP_Query – order by date, different sorting options

    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 a 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.

    Follow us for more useful tips and guidelines.

    Comments
    0 response

    Add comment

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

    Popular news

    A game changer for WooCommerce users
    • Our Highlights

    A game changer for WooCommerce users

    March 24, 2023 by createIT
    The differences between a web app and a mobile app
    • Services
    • Technology
    • Trends

    The differences between a web app and a mobile app

    March 7, 2023 by createIT
    Webrooming and showrooming
    • Trends

    Webrooming and showrooming

    February 14, 2023 by createIT
    PHPStorm – fix long load time of a directory window
    • Dev Tips and Tricks

    PHPStorm – fix long load time of a directory window

    January 20, 2023 by createIT
    reCAPTCHA v3 – WordPress implementation
    • Dev Tips and Tricks

    reCAPTCHA v3 – WordPress implementation

    January 20, 2023 by createIT
    How to compare GIT and server files
    • Dev Tips and Tricks

    How to compare GIT and server files

    January 19, 2023 by createIT
    How to trigger a click event inside iframe?
    • Dev Tips and Tricks

    How to trigger a click event inside iframe?

    January 19, 2023 by createIT
    FOOEvents – generate a custom CSV report
    • Dev Tips and Tricks

    FOOEvents – generate a custom CSV report

    January 19, 2023 by createIT
    Headless chrome – testing webgl using playwright
    • Dev Tips and Tricks

    Headless chrome – testing webgl using playwright

    January 18, 2023 by createIT
    Preview big SQL files with PilotEdit
    • Dev Tips and Tricks

    Preview big SQL files with PilotEdit

    January 18, 2023 by createIT

    Support – Tips and Tricks
    All tips in one place, and the database keeps growing. Stay up to date and optimize your work!

    Contact us