• Is there a quick way to get the most recent post’s ID? I know I can do it with the Loop, but I was wondering if there was a less intensive, quicker way of doing it.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Thread Starter maerk

    (@maerk)

    The solution is to use an ORDER BY clause to order the posts by date, and then set LIMIT 1 — so simple but I couldn’t see it!

    Uh, that’s all greek to me. Can anyone supply a line of code or modify the following so that the result is the ID of the latest post in a category? Right now I have this, which returns the total number of posts, but not an ID:

    $cat_count = $wpdb->get_var(“SELECT category_count from $wpdb->categories WHERE cat_ID = ‘2’”);

    Uh, that’s all greek to me.

    Actually, it’s SQL, not greek. ;)

    Kidding aside, this query bit will do what you want, though it’s not so much a mod of your line above as it is a completely new one:

    $postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON ID = post_id WHERE category_id = '2' ORDER BY post_date DESC LIMIT 1");

    Thanks so much! That does work, with one small modification: the category I was using was the default category, so page IDs were being mixed in with post IDs and some of the page IDs were higher. So, I created a new category, switched the posts to it, entered the new category ID in your line of code, and it works like a charm! For those who are curious, it is for the navigation bar at https://www.entropiacomics.com

    the category I was using was the default category, so page IDs were being mixed in with post IDs and some of the page IDs were higher.

    I like how you dealt with it, but wanted to note there’s a SQL solution for this problem:

    $postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON ID = post_id WHERE category_id = '2' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1");

    And a note to future, WordPress 2.1 (and up) users:

    $postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts LEFT JOIN $wpdb->post2cat ON ID = post_id WHERE category_id = '2' AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1");

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Fast way to get latest post’s ID?’ is closed to new replies.