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.

    Do you need someone to implement this solution for you? Check out our specialists for hire in the outsourcing section. Are you considering a global project and are uncertain how to proceed? See how we do it.

    Comments
    0 response

    Add comment

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

    Popular news

    Digital marketing without third-party cookies – new rules
    • Technology
    • Trends

    Digital marketing without third-party cookies – new rules

    February 21, 2024 by createIT
    eCommerce healthcheck
    • Services
    • Trends

    eCommerce healthcheck

    January 24, 2024 by createIT
    Live Visitor Count in WooCommerce with SSE
    • Dev Tips and Tricks

    Live Visitor Count in WooCommerce with SSE

    December 12, 2023 by createIT
    Calculate shipping costs programmatically in WooCommerce
    • Dev Tips and Tricks

    Calculate shipping costs programmatically in WooCommerce

    December 11, 2023 by createIT
    Designing a cookie consent modal certified by TCF IAB
    • Dev Tips and Tricks

    Designing a cookie consent modal certified by TCF IAB

    December 7, 2023 by createIT
    Understanding the IAB’s Global Vendor List (GVL)
    • Dev Tips and Tricks

    Understanding the IAB’s Global Vendor List (GVL)

    December 6, 2023 by createIT
    Effortlessly transform JSON data into a clear schema
    • Uncategorized

    Effortlessly transform JSON data into a clear schema

    December 5, 2023 by createIT
    Anatomy of WordPress malware: a technical deep dive
    • Dev Tips and Tricks
    • Technology

    Anatomy of WordPress malware: a technical deep dive

    December 4, 2023 by createIT
    Initializing CMP with the Stub Script and cmpapi.js
    • Dev Tips and Tricks

    Initializing CMP with the Stub Script and cmpapi.js

    November 29, 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