Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
$post_is[0]->ID You can't do this, unless you are running master branch of PHP I believe, just thought I would mention it if anyone was copy / pasting you example. If you wanted to do it in one line, you would have to do reset( $post_is )->ID –  Joe Hoyle Mar 21 '11 at 0:48
    
Also, if you pass an array to this function, it will result in a double array, instead you probably want to array cast the $cat variable: 'category__in' => (array) $cat –  Joe Hoyle Mar 21 '11 at 0:51
    
Awesome, did exactly what I was looking for, thanks! –  Jason Yost Mar 21 '11 at 1:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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