Get post ID outside of the loop

I am trying to accomplish something somewhat simple I think. I have a menu item at the top of my page that I want to link to the latest post in a certain category. I just need to get the post ID of the latest post in the category so I can pass it to the menu. I want to do this outside of the loop and create a function in functions.php that will return the post ID. Does anyone have any suggestions on how to do this?

Related posts

Leave a Reply

1 comment

  1. here is a function that does just that:

    function get_lastest_post_of_category($cat){
        $args = array( 'posts_per_page' => 1, 'order'=> 'DESC', 'orderby' => 'date', 'category__in' => (array)$cat);
        $post_is = get_posts( $args );
        return $post_is[0]->ID;
    }
    

    Usage: say my category id is 22 then:

    $last_post_ID = get_lastest_post_of_category(22);
    

    you can also pass an array of categories to this function.