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