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.
1
add_filter( 'asp_query_args', 'asp_posts_from_same_terms', 10, 2 );
2
function asp_posts_from_same_terms($args, $search_id) {
3
$taxonomies = 'category, post_tag'; // comma separated list of taxonomies
4
$allow_missing = false; // allow (empty) items with no connection to any of the taxonomy terms filter
5
$search_ids = 'all'; // comma separated list of search IDs, where the code should apply
6
7
// --- DO NOT CHANGE ANYTHING BELOW ---
8
$search_ids = explode(',', $search_ids);
9
foreach ( $search_ids as &$sid )
10
$sid = trim($sid);
11
if (
12
!empty($args['_page_id']) &&
13
( in_array('all', $search_ids) || in_array($search_id, $search_ids) )
14
) {
15
$taxonomies = explode(',', $taxonomies);
16
foreach ( $taxonomies as $taxonomy ) {
17
$taxonomy = trim($taxonomy);
18
$terms = wp_get_object_terms(
19
$args['_page_id'],
20
$taxonomy,
21
array('fields' => 'ids')
22
);
23
if ( !is_wp_error($terms) && count($terms) ) {
24
$args['post_tax_filter'][] = array(
25
'taxonomy' => $taxonomy, // taxonomy name
26
'include' => $terms, // array of taxonomy term IDs to include
27
'exclude' => array(),
28
'allow_empty' => $allow_missing // allow (empty) items with no connection to any of the taxonomy terms filter
29
);
30
}
31
}
32
}
33
return $args;
34
}
Copied!
  • $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.
Last modified 1yr ago
Copy link