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. Wordpress Rest API showing theme custom fields within the end point url are refusing to update via a post command
  2. Generate new post WordPress based on MySQL database
  3. Iframe (ads) is blur in Chrome when it is resized to fit in sidebar div
  4. How to make a WordPress page mobile responsive?
  5. Permalink Settings You should update your web.config now [on hold]
  6. how to upload image to wordpress with flutter using REST API
  7. Setting CSS property - filter: blur(x) with JS for site-inner class within genesis framework; Cannot read property 'getAttribute' of null
  8. Error on wordpress on my VPS: Your PHP installation appears to be missing the MySQL extension which is required by WordPress [on hold]
  9. Netlify deploy with results of TypeError: Cannot read property 'replace' of undefined
  10. How to position text at the same vertical level across columns

WordPress problems we are working on

  1. How to target a specific group on Buddypress (WordPress) to show it on a widget?
  2. Is it possible for Month names to be shown in my language
  3. Displaying and grouping posts
  4. Wordpress custom endpoints (WP_REST_Controller) 404 only on mobile
  5. Set default value in database [on hold]
  6. How do I programmatically set a user as spam in BuddyPress?
  7. Can i edit styling of form in ultimate member wordpress plugin?
  8. wordpress product attribute not creating automatically only work size and color other attributes not work need to add manually again same attribute
  9. Uncaught Error: Syntax error, unrecognized expression on WordPress website
  10. Wordpress website hacked and .htaccess file is creating automatically with strange code

Resolved issues

  1. Wordpress gutenberg editor gallery first image missing [on hold]
  2. how to fix the error No Input file specified on wordpress when using .php extention on pages
  3. How do I integrate Chargebee api to wordpress?
  4. Sorting a wp_query with more than one 'orderby'?
  5. Wordpress API: Sort posts by sticky and date
  6. Column background color not showing up
  7. How to show a row for each column?
  8. Wordpress site's frontend css styles not loading [on hold]
  9. Get the just added term_id (WordPress)
  10. Permalink structure does not get updated
wppotion - powered by persistence and passion