Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.