I’m looking to find a way to show the last 5 posts on the homepage of my WordPress website, so i assume i will need to utilise shortcodes to do this, however i cannot find any pre-existing code to add to functions.php that will show the title, date and post excerpt.
Could someone possibly help me with this?
There are a variety of ways to do this, but the basic idea is similar to the code you’ll see in your theme’s INDEX.PHP page. You do a query, loop through to show the posts, then reset the query at the end so what you did doesn’t interfere with your main page.
To register this as a widget, enable the “echo” at the end, then add this line to the bottom of your file:
You may want to add some extra code to place the output into a widget wrapper DIV like your other sidebar widgets. (Or, not if you use it somewhere besides a traditional sidebar.)
You could also register this as a shortcode handler using the line below. Comment out the “echo” at the end and uncomment the “return”.
You’ll want to make sure that you don’t use the shortcode in blog posts or you might end up calling this recursively. Probably a bad thing.
You’ll probably also want to add a theme-specific prefix to the function name to avoid namespace collisions.