I want to display in page the latest post content from a category.
For example, the category foo
has the following posts:
-
- Hello World
-
- Hello Mars
-
- Foo bar
Considering Foo Bar the latest article from foo category, its content should be rendered in a page:
<title>
<content>
Where <title>
is Foo bar and <content>
is the post content.
How can I do this?
I'm struggling to implement the @Pieter@Pieter's answer. I added these lines in functions.php
:
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>".$post->title."</h2>";
$str = $str."<p class='post-content-custom'>".$post->content."</p>";
endforeach;
return $str;
}
add_shortcode('latest_post', 'latest_post');
In the page I do:
[latest_post]
However, no error appears, but the post content doesn't appear.