WP_Query – order by date, different sorting options - createIT
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 in WordPress

    SOLUTION: Use meta_query parameter

    This article was checked and updated in August 2024 to make sure it’s up to date.

    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 );

    Understanding WP_Query Order By parameter in WordPress


    The WP_Query class in WordPress is an incredibly powerful tool that allows developers to create custom queries to interact with the database and retrieve posts based on specific criteria. One of the essential features of WP_Query is the order_by parameter, which determines the sorting order of the query results. This parameter can sort posts based on various fields such as post date, title, ID, author, and more. For instance, setting order_by to ‘date’ will organize the posts by their publication date. Additionally, order can be set to ‘ASC’ for ascending or ‘DESC’ for descending order. This level of customization helps developers display content in a precise order, enhancing the flexibility and functionality of WordPress themes and plugins.

    Summary – Now you know how to use wp query order by

    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 custom web application solution for you? Check out our specialists for hire in the outsourcing section.

    Comments
    0 response

    Add comment

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

    Popular news

    Fetching Time records from ActiveCollab API
    • Dev Tips and Tricks

    Fetching Time records from ActiveCollab API

    September 9, 2024 by createIT
    Docker Compose for PrestaShop
    • Dev Tips and Tricks

    Docker Compose for PrestaShop

    September 2, 2024 by createIT
    WordPress wizard in admin – step by step
    • Dev Tips and Tricks

    WordPress wizard in admin – step by step

    August 29, 2024 by createIT
    Order Status Sync between PrestaShop and External APIs
    • Dev Tips and Tricks

    Order Status Sync between PrestaShop and External APIs

    August 26, 2024 by createIT
    What is PHP used for in web development 
    • Dev Tips and Tricks

    What is PHP used for in web development 

    August 22, 2024 by createIT
    Automating WooCommerce product availability date
    • Dev Tips and Tricks

    Automating WooCommerce product availability date

    August 15, 2024 by createIT
    WP Quiz Adventure – FAQ
    • Dev Tips and Tricks

    WP Quiz Adventure – FAQ

    August 12, 2024 by createIT
    Retrieval Augmented Generation tutorial and OpenAI example
    • Dev Tips and Tricks

    Retrieval Augmented Generation tutorial and OpenAI example

    August 8, 2024 by createIT
    10 useful SEO tools for the iGaming industry
    • Services
    • Technology

    10 useful SEO tools for the iGaming industry

    August 5, 2024 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