In this weeks tutorial I am going to teach you how to create a shortcode to display your posts in WordPress. This technique is useful as it allows you to display the latest posts in the content of your pages or posts, I even use this to display the posts on the homepage of this site. Lets get stuck in.
Lets first learn about the WordPress loop.
The loop is an integral part of any WordPress site as it is used to display not only posts, but page content too.
Here is a simple loop.
There are no posts to display
The first line checks if there are posts available. The second line will then start to display the posts. The third line will display the title. The fourth line will display the content, and the text in parenthesis will be the link to the single post. The fifth line will end the posts. The next three lines will display if there are no posts to show and will acts as a fallback when there are no posts available.
We now need to add that to a shortcode. If you are unsure on how to create a shortcode then refer back to my earlier post on creating a shortcode.
Lets create the main function to display the shortcode.
id="post-">There are no posts to display
Now you will see the earlier loop within this code which will display a list of posts, and is controlled using the setting in Settings > Reading > Blog pages show at most.
Now all you need to do is then use the following shortcode to display your posts.
Now you should be able to display your posts on any of your posts or pages, using the above shortcode. Let me know if you find this useful in the comments below.