If you enjoy reading blogs, then you’ve probably noticed that many will have a “Related Posts” section at the end of a post. Displaying related posts is a great way not only to promote more of your website content, but also to create internal linking on site which helps with SEO efforts. There are countless WordPress plugins that will do this for you. However, if you are like me and like to use as few plugins as possible, then you can quickly create some related posts using a plugin that you may already be using: Advanced Custom Fields.
Setting Up the Custom Field
The first thing to do is to create a Relationship custom field. When setting up the custom field, you will be able to select which post types you would like to use as potential related posts and well as specific taxonomies (if you wanted to limit to a specific category for example). For this example, we will keep it simple and allow any and all post types and taxonomies.
When the custom field is created, it should look something like this:
Choosing Which Posts to Display
Once you have the custom field created, you can now choose which related posts you would like to display on a given post. You’ll notice that on the left hand side of the custom field is a list of all the available posts that you can include. Simply click on the ones you’d like to show up, and they will be added to the right hand side. It should look something like this:
That’s it! The only thing left to do is add the code that will handle this custom field.
All-new Echo (2nd Gen) has a new speaker, new design, and is available in a range of styles including fabrics and wood veneers. Echo connects to Alexa to play music, make calls, set music alarms and timers, ask questions, control smart home devices, and more—instantly.
The code to display these posts is fairly straightforward. Basically, it will be a custom query that loops through all of the posts and grabs the ones that have been selected. Here is the code for the custom query:
That’s all there is to it. Let’s break this down a bit. Basically, the variable of
$posts returns an array of the IDs of the posts that have been chosen to display. That variable is then used to filter the posts by using the
"post__in" parameter. What’s left are only the posts selected with the custom field. Pretty great, right?
Again, there are a ton of plugins out there that can add related posts. Some of them can even systematically select posts for you. However, if you are looking to keep your plugin count low, this is a good solution for you.
Was this helpful? Let me know in the comments below!