Created
September 16, 2015 15:22
-
-
Save kraftbj/9711eaed13e4cf13524e to your computer and use it in GitHub Desktop.
Related Posts: Only return posts in same categories
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
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 ?