How to show related posts from the same subcategory


It looks like related posts in WordPress slowly becomes a very popular topic to discuss. Recently we worked on a few cases in which we had to display related posts under different conditions. One of them was not show similar posts from the same subcategory, but skip the parent category. The described case was quite interesting, so we would like to share it with you. In the following tutorial we will share how to display related posts by subcategory. If you are interested in related posts by category, just click here

Related posts – preparations

Here are the preparations that took place:

  1. We installed WordPress for testing purposes
  2. Added 2 main categories with several subcategories
  3. No additional plugins were installed
  4. We used test theme without any additional features

The first stage of the task was to identify the category our post belongs to and its parent. To do so we used the following piece of code which is based on the result of get_the_category and simple foreach loop. Its idea is to repeat the same thing for each element in an array. The original piece of code is as follows:

<?php 


$getcategories = get_the_category();
foreach( $getcategories as $category ){
 $sub_category = $category;
echo '<pre>';

print_r($category);

echo '</pre>';
}

For better visualization we deliberately added print_r statement in order to review the array WordPress passed back. The result can be seen on the following screenshot:

Custom related posts

Custom related posts

We see that our subcategory ID is 38 and its parent category ID is 35. We also see 3 items in the current subcategory. The name of our subcategory is Cat1Sub2.

Code customisation

The next step is to display  the subcategory name in accordance with its ID and then prepare a list of the items in it making sure that the current post ID is excluded from the list. Here is how to do it:

if( isset( $sub_category ) ){ 
 echo '<b>more items in: </b>' . $sub_category->name;
 $args = array(
 'cat' => $sub_category->term_id,
 'post__not_in' => array( get_the_ID() )
 );
 $relatedpostsinsubcategory = new WP_Query( $args );
 if( $relatedpostsinsubcategory->have_posts() ){
 while( $relatedpostsinsubcategory->have_posts() ){
 $relatedpostsinsubcategory->the_post();
 
 ?>
 <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> 
<?php
 }
 wp_reset_postdata();
 }
}

To avoid issues with the code and possible syntax errors on your page, you have to read carefully  the code and switch from PHP to HTML very carefully. When you want to print some HTML elements, you have to close PHP tags and then open them again. Of course you can use echo for the said elements, but our example is a bit more basic, so we used simplified version for this tutorial.

The second piece of code gets the current category ID and passes arguments to it. As we said, we need to exclude the current post ID from the results. Then we get the title of the remaining posts and display them as clickable links using the_title function.

The final result of the whole code adjustment can be seen on the following screen shot. To keeps the things clean, you may remove print_r statements as it was used for testing purposes only.

Related posts from subcategory

Related posts from subcategory

Summary
Related posts by subcategory in wordpress - custom solution
Article Name
Related posts by subcategory in wordpress - custom solution
Description
How to show related posts by subcategory in wordpress - code customisation - preparation and solution. Easy way to extract parent and subcategory IDs using native wordpress functions.
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. Can't Install Security Certificate with Apache
  2. Unique list of meta_values by multiple specific meta_key. Possible in Word Press?
  3. How to fadeup words each with a little delay to make a great headline
  4. Wordpress - Filter data from an external API
  5. MySQL won't start on Bitnami EC2 instance
  6. How to display the last four blog posts using Json api on html
  7. How can I include WordPress search results inside a post?
  8. Execute a plugin-installed WP-CLI command with Docker Compose
  9. Can anyone please help me to make a custom database in wordpress?
  10. WordPress Child Page Menu

WordPress problems we are working on

  1. How Do you Properly Add An Image Control To Wordpress Customizer?
  2. Centering image captions in the Gutenberg editor
  3. Catch Infinite Scroll plugin
  4. Wordpress Shortcodes only displayed on posts
  5. Wordpress add_rewrite_rule not working with pagination
  6. Wordpress AJAX load more check end of posts
  7. how to create section inside a section uisng wp_customize function in wrodpress
  8. Drag & Drop trashed error in Wordpress site [on hold]
  9. Once user sign in they are directed to a gravity form - only when it is complete will they be directed to the site
  10. Bootstrap 4 dropdown menu disappears on hover on Microsoft Surface only

Resolved issues

  1. WordPress multisite different user registration for different sites
  2. WP_Query::posts orderby doesn't preserve order of post__in
  3. How to fix 'null value of add_setting()'
  4. How to create the following detail in Wordpress
  5. migrating wordpress website from localhost in windows to centos7
  6. How to add %custom-taxonomy% to permalink (e.g. %subject% which is one we created)
  7. How to hide continue shopping after customer selects the second product
  8. Use styling and behavior on tags input that exists on back-end but on a front-end form
  9. WordPress Edit Page Fails with “TypeError: Converting circular structure to JSON”
  10. Wordpress REST API: failurejava.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
wppotion - powered by persistence and passion