How to display related posts by category


Related posts – how to easily display similar posts

In the tutorial titled WordPress related posts without plugin I explained how important are the contextual posts also known as related.  A simple piece of code designed to interact with the database and get similar posts could make your website much more visited and attract the visitors to stay longer on your page. Today we will continue working in the same direction and demonstrate how to display related posts by category using a custom plugin.

In this tutorial I will show you how to build a simple plugin that has its own header information, customized loop, function, hook and style. I will also show you how to enqueue a custom style.css directly into WordPress engine, so that our related posts look a bit better. The criteria we use is the category our post belongs to. In short, our loop will detect the current category, then it will select two posts and display their titles making sure they are published.

Building a custom plugin to display related posts by category

So now, let’s proceed with the preparations. Here is what you need to do:

  • Create a new folder inside plugins folder. You can name it whatever you want. Mine is basic-plugin
  • Now create a new file inside that folder and name it the same way. My file is  basic-plugin.php
  • Create one more file for the styling and add this line to it:
.related-post   {background-color: #aaa;margin-bottom: 10px;}
  • In this particular case my file is wp_style.css .

Now we are ready to start developing our plugin and give it some functionality. Let’s open the newly create php file and add the following code to it:

<?php

/*

Plugin Name: WPP Related articles

Plugin URI:  https://wppotion.com

Description: The plugin displays related posts by category

Version:     1.0

Author:      Leo

Author URI:  https://wppotion.com

License:     GPL2

License URI: https://www.gnu.org/licenses/gpl-2.0.html

*/




add_action( 'loop_end', 'custom_wpp_related_posts' );

function custom_wpp_related_posts (){

global $post;

$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 2,'post_status' => 'publish', 'post__not_in' => array($post->ID) ) );

if( $related )

if ( is_singular() ) {

 foreach( $related as $post ) {

setup_postdata($post);

echo '<div class="related-post"><a href="';

                the_permalink();

                echo '">';

                the_title();

                echo '</a>';

                echo '</div>';

               

}

}

}

wp_reset_postdata();
function basic_plugin_scripts() {

   wp_enqueue_style('basic_plugin_scripts', plugin_dir_url( __FILE__ ) . '/wp_style.css' );

}

add_action( 'wp_enqueue_scripts', 'basic_plugin_scripts' );

?>

Perhaps you have noticed that the code starts with comments block. It is required by WordPress. In essence it informs the engine that the file is actually a plugin and asks to be treated this way. The information it contains defines the plugin name which should be something unique in order to avoid unexpected behavior, plugin URI, Description, Author, Author URI, License and License URI .

As a little test, you may remove all of the custom functions and leave the header only. After that you can access wp-admin section of your WordPress instance and check Plugins section. There you will find your plugin listed as shown below:

Plugin header

Plugin header

As you can see author name and visit plugin page are clickable buttons. This is because we defined URIs . There you will also find activate, deactivate and delete options which means that WordPress recognizes your file as functional plugin.

Custom plugin hooks

Right after the header section we define our action hook in which we say in the end of each loop WordPress has to trigger a custom function named custom_wpp_related_posts. Before proceeding further I would like to say a few words about the hooks. There are two main hooks actions and filters. The actions can be triggered at certain point and perform some action such as applying a function while filters work differently. They are designed to check the output WordPress returns and modify it in some way. For example you can easily replace words, but this will be explained later in another tutorial.

So far, we defined a hook and function, but in order to display related posts by category, we need to develop a function to check our database and get the data we need. In the code of our function we use global $post  and then using get_posts we are looking for posts in the same category. We also define maximum number which is 2, check their statuses and also exclude the current post from the results.

After this query we define two if statements. The first one checks if we have some data in our variable and then the second one checks if the page is singular. The second if statement is actually an extra check because we do not want to display related posts on every page, but on posts pages.

The expected information stored in our variable is objects in array, so in order to build our list of related posts by category, we need to loop through the results and build the list. To do so we use foreach loop and print some HTML code as well as titles represented a links. In the end of the code we reset the data to avoid collisions with the data flow that is coming from the default WordPress loop.

Custom plugin checks

Now it is time to make another test and check our code. The purpose is to verify what data we get right after get_posts execution. To perform the check, just add the following code

echo '<pre>';

print_r($related);

echo '</pre>';

below:

if( $related ):

When you add the code, save the changes and refresh the page. Note that the layout might be a bit broken, but do not worry. If the changes are applied correctly you will see output similar to this one:

WordPress objects in an array

WordPress objects in an array

We see two objects in an array with all the information that is saved in the database including post ID, author, post date, status and so on. If you want to display more related articles or review more objects, just update numberposts from 2 to 3,4,5 or even more.

Now we can review the final part of our custom plugin. It is designed to load a simple CSS file located in the root folder of the plugin we are working on. To do so we use wp_enqueue_style function. It accepts 5 parameters, but we will define only two- the name of the CSS and its location. The name comes from our function. To determine the full path to the file we are injecting, we use plugin_dir_url function. The final step is triggering this custom function. To do so, we again use an action hook that enqueues our function.

If everything is correctly created and saved, the plugin we develop should be working fine. Here is how it acts on my test WordPress instance:

Custom plugin to display related posts by category

Custom plugin to display related posts by category

The lines in darker color are two related posts from the same category. I can see that the loop described above, properly connects the database. It also identifies the category of the post and retrieves the latest posts.

Summary
How to display related posts by category
Article Name
How to display related posts by category
Description
How to display related posts by category using a custom plugin
Author
Publisher Name
wppotion


Do you want to share your opinion?

Your email address will not be published. Required fields are marked *


*

We are not industry specific. We are WordPress specific. We work with everyone to help them find solutions with their troubles.
If you show us the problem you are experiencing, we will show you how to fix it. It is that simple.


Reported WordPress issues

  1. which wordpress plugin is used for seo?
  2. How to add custom field for each post object [acf]
  3. Add if statement to a class in php in wordpress
  4. Wordpress theme installation : BLU Theme
  5. Resource for hosting part of a web site on another server
  6. how can i get wordpress to understand my custom theme is not a child theme?
  7. Wordpress - exclude priviously displayed posts (set offset)
  8. What are the reasons why the translated text is not displayed in the plugin?
  9. Site not responsive on some pages in mobile
  10. Error sending data to php with ajax in wordpress

WordPress problems we are working on

  1. Wordpress Subfolder Shows 404 Which Has File Hosting PHP script
  2. WordPress API media query returning all file types except jpeg
  3. Extra Coding with JW Player 7
  4. Redirect function for WP User Switching plugin
  5. How to display errors under adequate fields on a login form?
  6. Wordpress site displays replacement character � in posts
  7. WordPress REST API - more than 10 posts
  8. Add visual composer to textarea wordpress
  9. Automatic AdSense stopped showing - error 400 ()
  10. How to add meta tags in Wordpress for each post

Resolved issues

  1. Call wordpress function get_stylesheet_directory from a plugin's main php file
  2. Wordpress Events Manager point events on picture
  3. Toggle button (Area-expanded)
  4. Advanced Custom Fields Pro (ACF) field type with Download Monitor library
  5. Wordpress Session Variable exist but not working when i access in plugin wp-estore
  6. How to upload multiple images to current post from front end?
  7. contact form 7 set acceptance checkbox line an optional
  8. Wordpress pagination on Custom Post Type not working
  9. Cannot get rid of unwanted favicon - Wordpress site
  10. Creating a Wordpress Widget from another theme
wppotion - powered by persistence and passion