7

Been all over looking for the best way to do this.

I want to get the ID of the latest post of a certain post_type.

How can I do this in the cheapest way possible (by cheapest I mean using the least queries, and no loops or post rewinding)?

Surely there is a quick method?

19
$latest_cpt = get_posts("post_type=yourcpt&numberposts=1");
echo $latest_cpt[0]->ID

The only cheaper way than above, I can think of, would be to write your own SQL query to just return the one post and only the column ID.

  • Yes, that's it! I've been skirting around it. Thanks @brady – Niels Sep 7 '11 at 7:35
  • 2
    get_posts("post_type=yourcpt&numberposts=1&fields=ids") to only return the post id, nothing else, a little bit faster this way:) – passatgt Jun 12 '15 at 9:30
  • post_type=post to get default posts. – Travis van der Font Jun 11 '18 at 10:27
1

A more pure SQL way:

function GetLastPostId()
{
    global $wpdb;

    $query = "SELECT ID FROM $wpdb->posts ORDER BY ID DESC LIMIT 0,1";

    $result = $wpdb->get_results($query);
    $row = $result[0];
    $id = $row->ID;

    return $id;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.