You can make use of WP_Query
to call the lastest post from the category and display it. Have a look at the category parameters. By default, WP_Query
uses post
as the post type and orders post by post date, so we can exclude that from the query. If you need something else, you can just define them in you arguments
You can basically try something like this
$args = array(
'posts_per_page' => 1, // we need only the latest post, so get that post only
'cat' => 'ID OF THE CATEGORY', // Use the category id, can also replace with category_name which uses category slug
//'category_name' => 'SLUG OF FOO CATEGORY,
);
$q = new WP_Query( $args);
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
//Your template tags and markup like:
the_title();
}
wp_reset_postdata();
}
This should provide you with a base, you can modify, customize and use it as you like. If you are unsure of the parameters and usage, check out the WP_Query
codex page for assistance
EDIT
I’m really not sure why you decided to reinvent the wheel and to go with get_posts
where as I have showed you a working example of how to use WP_Query
. Your use of get_posts
in conjuction with the WP_Post
properties is completely wrong
-
The
WP_Post
properties is unfiltered, so the output from this is totally unfiltered and will not look the same as the output from the template tags likethe_title()
orthe_content()
. You have to use the appropriate filters on those properties -
title
andcontent
is invalid properties ofWP_POST
. The other answer is completely wrong. It ispost_title
andpost_content
-
You can make use of the template tags as normal by just using
setup_postdata( $post );
and then just usingwp_reset_postdata()
afterwards
You can try the following
function latest_post() {
$args = array(
'posts_per_page' => 1, // we need only the latest post, so get that post only
'cat' => '4' // Use the category id, can also replace with category_name which uses category slug
);
$str = "";
$posts = get_posts($args);
foreach($posts as $post):
$str = $str."<h2>". apply_filters( 'the_title', $post->post_title) ."</h2>";
$str = $str."<p class="post-content-custom">". apply_filters( 'the_content', $post->post_content ) ."</p>";
endforeach;
return $str;
}
add_shortcode('latest_post', 'latest_post');