11 August 2016 (age 26) Web

Jetpack: Only show related posts from the same category

The Jetpack plugin is a must-have for almost any WordPress website. It may be bloated with all kinds of crap you don’t need, but it always has one or two features you absolutely do need. And it tends to do those things quite well (security protection, stats, social media sharing). It’s no wonder that major theme developers are relying on Jetpack instead of reinventing the wheel.

So I thought it was really weird when I couldn’t find any information about what I thought would be a common problem. Jetpack’s Related Posts finds relevant content suggestions at the bottom of a blog post. I wanted to make sure those suggestions are coming from the same category as the current post.

Searches on Google? Nothing. Stack overflow? Nada. WordPress forums? Zilch. Jetpack’s own website recommended taking a look at the source code, which left me scratching my head.

At long last, I emailed the Jetpack support team and they provided me with some code to use. It was half-complete, but gave me enough new keywords to look up that I came across this solution by Brandon Kraft:

// This function will only return posts that are related AND has ALL of the same categories.
function jp_only_rp_in_same_category( $categories, $post_id ) {
  $category_objects = get_the_category( $post_id );
  if ( ! empty( $categories ) ) {
      $categories = array_merge( 'categories', 'category_objects' );
      return $categories;
  }
  else {
    return $category_objects;
  }
}
add_filter( 'jetpack_relatedposts_filter_has_terms', 'jp_only_rp_in_same_category', 10, 2 );

Copy and paste that into your functions.php or wrap it in a simple plugin, and you’re good to go.

Sam Nabi

Comments

Post a comment

Comments are closed.