Restricting results to the same category as the current post object

Limiting posts, pages, products or any custom post type results to only categories, or any taxonomy terms - where the post type object (post, page, product etc..) belongs to.

What is this, and where do I put this custom code?

add_filter( 'asp_query_args', 'asp_posts_from_same_terms', 10, 2 );
function asp_posts_from_same_terms($args, $search_id) {
$taxonomies = 'category, post_tag'; // comma separated list of taxonomies
$allow_missing = false; // allow (empty) items with no connection to any of the taxonomy terms filter
$search_ids = 'all'; // comma separated list of search IDs, where the code should apply
// --- DO NOT CHANGE ANYTHING BELOW ---
$search_ids = explode(',', $search_ids);
foreach ( $search_ids as &$sid )
$sid = trim($sid);
if (
!empty($args['_page_id']) &&
( in_array('all', $search_ids) || in_array($search_id, $search_ids) )
) {
$taxonomies = explode(',', $taxonomies);
foreach ( $taxonomies as $taxonomy ) {
$taxonomy = trim($taxonomy);
$terms = wp_get_object_terms(
$args['_page_id'],
$taxonomy,
array('fields' => 'ids')
);
if ( !is_wp_error($terms) && count($terms) ) {
$args['post_tax_filter'][] = array(
'taxonomy' => $taxonomy, // taxonomy name
'include' => $terms, // array of taxonomy term IDs to include
'exclude' => array(),
'allow_empty' => $allow_missing // allow (empty) items with no connection to any of the taxonomy terms filter
);
}
}
}
return $args;
}
  • $taxonomies (string) - comma separated list of taxonomies, where this code should apply to

  • $allow_missing (boolean) - in cases, when the resulting objects (posts, pages etc..) does not have the taxonomy assigned - should they be allowed as results. Ex.: Current page belongs to post_tag named Tag1. The search is configured to search posts and products as well, but products can not have assigned items from post_tag taxonomy. When $allow_missing = false; (default), all of the products will be excluded.

  • $search_ids (string) - comma separated list of serach IDs, where the code should apply on. Assigning 'all' (default) value will apply on all search bars.