WordPress.org

Ready to get started?Download WordPress

Forums

Fast way to get latest post's ID? (6 posts)

  1. maerk
    Member
    Posted 8 years ago #

    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.

  2. maerk
    Member
    Posted 8 years ago #

    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!

  3. superiorstudio
    Member
    Posted 7 years ago #

    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'");

  4. Kafkaesqui

    Posted 7 years ago #

    "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");

  5. superiorstudio
    Member
    Posted 7 years ago #

    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 http://www.entropiacomics.com

  6. Kafkaesqui

    Posted 7 years ago #

    "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");

Topic Closed

This topic has been closed to new replies.

About this Topic