Skip to content

Instantly share code, notes, and snippets.

@kraftbj
Created September 16, 2015 15:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraftbj/9711eaed13e4cf13524e to your computer and use it in GitHub Desktop.
Save kraftbj/9711eaed13e4cf13524e to your computer and use it in GitHub Desktop.
Related Posts: Only return posts in same categories
<?php // do not include this line if pasting into an existing php file
// 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 );
// This one will limit it to a specific category.
function jp_only_rp_in_certain_category( $categories, $post_id ) {
if ( in_category( 'techy-tips' ) ) { // using a category slug, could be ID, an array of IDs, etc
$categories = array( get_category_by_slug( 'techy-tips' ) );
}
return $categories;
}
add_filter( 'jetpack_relatedposts_filter_has_terms', 'jp_only_rp_in_certain_category', 10, 2 );
@mahaweilu
Copy link

hello, I have tried these codes for my wordpress site but it doesn't work. I found some related issues here, it seems Jetpack don't support the filter function now.

Could you please share your current solution about how to return the posts in a same category ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment