How to Show Related Post by Child Category in WordPress?

Updated on May 6, 2023 by Editorial Team

Table of Contents

Showing related posts by child category can help improve the user experience on your WordPress site by providing more relevant content to your visitors. By displaying related posts based on the child category of the current post, you can keep your readers engaged and encourage them to explore more of your content.

To achieve this, you can use the Post Listing block from The Plus Blocks for Gutenberg.

To check the complete feature overview documentation of The Plus Blocks for Gutenberg Post Listing block, click here.

Requirement  – This block is a part of The Plus Blocks for Gutenberg, make sure its installed & activated to enjoy all its powers.

By default, in WordPress, there is no option to show related posts by a child category. For this, you have to add some custom code. You can add the code in your Child theme function.php file or you can use plugins like Code Snippets to add your custom code or if you are using the Nexter theme you can use Nexter Extensions which comes with various extensions for your Theme including adding code snippets.

Note: This feature is for advanced users only. If you are comfortable with PHP only, then you should use it.

For example, we have added this code.

add_filter('tpgb_custom_doc_query', 'tpgb_custom_doc_query_function',10,1);

function tpgb_custom_doc_query_function( $query_args ){
    
    global $post;
    $category_ids = [];
    $categories = isset($post->ID) ? wp_get_post_terms($post->ID,'docs') : [];
    foreach($categories as $category) {
   	 if( 0 != $category->parent ){
   		 $category_ids[] = $category->slug;
   	 }
   	 
    }
    
    if(isset( $query_args['tax_query'] ) && !empty($query_args['tax_query'])){
   	 foreach( $query_args['tax_query']  as $key => $argc) {
   		 if($argc['taxonomy'] == 'docs' ){
   			 $query_args['tax_query'][$key]['terms'] = $category_ids;
   			 
   		 }
   	 }
    }
    return $query_args;
}

Now to show related posts by child category based on this code, add the Post Listing block on the page or template, and select the appropriate listing type, post type, style and layout.

Then go to the Query tab and in the Custom Query ID field, add the filter key i.e. tpgb_custom_doc_query here. 

post listing custom query id

Now it will show related posts by child category.

Also, check How to Show Related Posts for Custom Post Type in WordPress.