Specific Category for Jetpack Related Posts

I’m really impressed with Automattic’s Jetpack, and have recently used it for one of my clients. We’re using the Related Posts module to show 3 related posts at the bottom of each single post, and while that’s fine for many of their categories, this client wanted a featured category to only show other posts from this featured category as the related items.

While there is a way to exclude a category from showing up in Related Posts, there has been no documented way to only use one specific category for Related Posts. However, it is possible by excluding all categories except for the featured category. Here’s the code!

For this code, my featured category has an ID of 721. This code makes it so posts in category 721 will only get related posts from category 721.

function jetpackme_filter_exclude_category( $filters ) {
if(in_category('721')) {
  $args = 'exclude=721';
    $categories = get_categories( $args );
    foreach($categories as $category) {
        $filters[] = array( 'not' => array( 'term' => array( 'category.slug' => $category->slug ) ) );
     }
}
    return $filters;
}
add_filter( 'jetpack_relatedposts_filter_filters', 'jetpackme_filter_exclude_category' );

You can repeat lines 2-8 for each category that you need to isolate.

7 comments on “Specific Category for Jetpack Related PostsAdd yours →

    1. Hi Rodolfo,

      I did a few tests and I’m finding that this won’t work if the category ID is for a subcategory (because you can’t exclude the parent category — a catch 22!).

      Is your category with ID 24 a subcategory or a parent category? Another caveat is that the category has to have enough posts in it to show the proper related posts.

      Hope this helps!

      1. Now that I think of, in this part:

        $args = ‘exclude=24’;
        $categories = get_categories( $args );

        …the excluded categories are 1 other parent and its children. Are you saying it won’t detect the children but only their parent?

    2. Hi Rodolfo,

      This code snippet is intended to make all posts in category 24 ONLY show other posts in category 24 in the results for Jetpack’s Related Posts module. Other categories will just show related posts from whatever Related Posts generates, regardless of the category.

      Yes, it goes into your theme’s functions.php.

      What is it that you need to make happen? If you need to exclude a category from all Related Posts output, you can find the code here: http://jetpack.me/support/customize-related-posts/#exclude-cats

      If you need more help, feel free to e-mail me at mercy@mercytapscott.com or add me on Skype (just search for Mercy Tapscott).

      Good luck!

Leave a Reply