Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top