Home › Forums › Product Support Forums › Ajax Search Pro for WordPress Support › Category wise search › Reply To: Category wise search
Hi,
It is possible to restrict the results to the current category of the page via this custom code snippet.
However in your case it may be a bit more complicated as using the category shortcode does not indicate which category the page is in – they are not connected in any way. To do that, you would have to create a programmatical map (array) of pages and product categories it should restrict. I’m thinking using this example as the base.
Here is a super simple custom code that should do the trick. You want to change the $page_rules variable, you can add as many lines as you want. On the left side is the page ID, on the right side is the category ID to which you want to restrict the search results to on that given page.
add_filter( 'asp_query_args', 'asp_include_only_term_ids', 10, 2 );
function asp_include_only_term_ids( $args, $id ) {
/**
* Format: page_id => product category it should be restricted to
* For example, if you want to restrict page ID 123 to category ID 5: 123 => 5,
* You can add as many lines as you want
*/
$page_rules = array(
123 => '5',
456 => '6',
);
// -- !! Do not change anything below this line !! --
if ( !is_array($args['post_tax_filter']) ) {
$args['post_tax_filter'] = array();
}
foreach ( $page_rules as $page_id => $term_string ) {
if ( $page_id !== intval($args['_page_id']) ) {
continue;
}
$terms = explode(',', $term_string);
foreach ( $terms as $tk => &$tv ) {
$tv = trim($tv);
}
$args['post_tax_filter'][] = array(
'taxonomy' => 'product_cat',
'include' => $terms,
'allow_empty' => false,
);
}
return $args;
}
I’m more than happy to help, but please note that this level of customization is beyond support, so I can’t guarantee anything. If you want professional customizations, I recommend our affiliates at wpkraken.
Try adding this code via the Code Snippets plugin or to the functions.php file in your theme/child theme directory – make sure to have a full server back-up first for safety. For more details you can check the safe coding guidelines.