How to get a custom post with the largest ID (not the last post by date)

I would like to get the (one) post with the last ID, even if it is not the last post by date. The post belongs to a custom post type.

I need this to assign custom id numbers to my orders. When creating a new order, I am going to find the post with the largest ID, get its order number from its meta, increment it and assign it to the new one. I DO UPDATE order post when order gets changed in any way and update its date to make it appear at the top of the post list. Therefore, the last post by date that WP gets does not necessarily have the largest ID number. I would like to get the post with the largest post ID.

This is an example list of my post ids

3460
3465
3464
3463
3462
3461
3459

I need to get 3465

This is my code:

$args = array(
   'post_type' => 'my_order_cpt',
   'post_status' => array('confirmed', 'paid', ..... , 'closed'),
   'numberposts' => 1,
   'orderby' => 'ID',
   'order'   => 'DESC'
);
$numbers = get_posts($args);

However, this gives me the last post by date. In my exaple, it’s 3460.

All the answers I found, e.g. here, describe getting the last post by date.

I know there’s a way to do this with a wpdb query (“SELECT meta_value FROM wp_postmeta WHERE meta_key='[plugin_prefix]_order_number’ ORDER BY CAST(meta_value AS UNSIGNED) DESC LIMIT 1″ + checking if post is not a draft and not in trash) or by getting all posts of the post type and playing with the array, but is there a way with get_posts()? Maybe, with meta_query? The order number is a separate meta field named ‘[plugin_prefix]_order_number’.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Turns out, I was kind of wrong when I tried to get the largest ID. What I needed was to get posts by, and then to sort by, the order number itself! Here’s what I came up with:

$num_args = array(
    'post_type' => 'my_store_order',
    'post_status' => array('mystatus_1', 'mystatus_2', 'mystatus_N'),
    'numberposts' => 1,
    'meta_query' => array(
        'my_clause' => array(
            'key' => 'my_order_number',
            'type' => 'numeric',
            'compare' => 'EXIST'
        )
    ),
    'orderby' => 'my_clause',
    'order' => 'DESC'
);

Also, since post meta is a string, I added ‘type’ => ‘numeric’ so when being sorted it would be treated as a number (1,2,10 vs 1,10,2)

This post helped me a lot


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x