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. Content Management System that works like a paid library?
  2. Visual editor more tag
  3. Wordpress - user uploads article with url only
  4. W3tc Eliminate render-blocking resources, wp-content/cache/minify/d9b67.default.include.39bb06.css?
  5. Wordpress Customize not working - load-scripts.php errors
  6. how pass shortcode parameter variable to theme file?
  7. How to add WP variables to GD imagepng
  8. WordPress page leave too much space
  9. Elementor pop up box
  10. Embedded maps showing as blank space on Wordpress site

WordPress problems we are working on

  1. How and where to write a logic to append strings at the end of an external link in wordpress blog posts
  2. Assign template to a post type via Javascript
  3. Is it possible to build a reccomendation engine in Wordpress based on $wpdb class and SQL? [on hold]
  4. Wordpress Paid Membership Pro recurring payments with Strip payment not working
  5. How pass WordPress shortcode with Parameters to template
  6. Translate Maintenance Pro Plugin WordPress
  7. Wordpress Admin Can't Login - ERROR: Cookies are blocked or not supported by your browser
  8. Javascript, Open/Close function
  9. How to make a search function with dropdown?
  10. How to store cookie value as a variable in Ionic 3 WordPress API -

Resolved issues

  1. CSS skewed sub-menu items displaying incorrectly
  2. Vue.js Axios Wordpress call
  3. How to get multipal post type archive?
  4. Wordpress PHP proper way to select row from table
  5. Implementing a user specific editable calendar
  6. Square POS integration into WordPress
  7. WPBakery post grid “Narrow data source” only shows “Uncategorized” on some pages/posts
  8. How to dedect if custom field contains a mp4 file in wordpress?
  9. How add support shortcode in textarea in theme [on hold]
  10. How to integrate drag page builder to own wp theme
wppotion - powered by persistence and passion