Get permalink to latest post in category

by vonnie   Last Updated September 11, 2019 17:08 PM

I need to get the permalink to the latest post in just one category. That link then needs to be placed into a button. The button is rendered within a function in a custom front-page.php template.

I have this so far but it is not working with various permutations and no errors are showing up:

$latest_post = get_post( array( 'cat' => 3, 'posts_per_page' => 1) );
if( $latest_post ) {
    echo '<a href= "' . get_permalink( $latest_post->ID ) . '">Learn More Now</a>';
}

Can anyone help show me where I've gone wrong?

Tags : categories


Answers 1


The function you are using here, get_post() does not accept query arguments. So you have to use get_posts(). Try this:

$latest_post = get_posts( array( 'cat' => 3, 'posts_per_page' => 1) );
if( !empty( $latest_post ) ) {
    echo '<a href= "' . get_permalink( $latest_post[0] ) . '">Learn More Now</a>';
}
Sohan Zaman
Sohan Zaman
September 11, 2019 17:03 PM

Related Questions


Updated May 27, 2015 00:03 AM

Updated October 02, 2017 10:08 AM

Updated January 23, 2019 11:08 AM

Updated June 30, 2016 08:03 AM

Updated October 20, 2017 08:08 AM