Last active
October 20, 2022 10:39
-
-
Save opicron/1ebfeb7c73729071e94d9a30996e4497 to your computer and use it in GitHub Desktop.
SearchWP custom search grouped/child #php #searchwp
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 | |
//Exclude child products from searches | |
function my_searchwp_exclude( $ids, $engine, $terms ){ | |
$excluded_product_ids = get_posts( array( | |
'post_type' => 'product', | |
'nopaging' => true, | |
'fields' => 'ids', | |
'meta_query' => array( | |
array( | |
'key' => '_children', | |
'value' => '', | |
'compare' => 'NOT EXISTS' | |
) | |
), | |
)); | |
$ids = array_merge( $ids, $excluded_product_ids ); | |
return $ids; | |
} | |
add_filter( 'searchwp_exclude', 'my_searchwp_exclude', 10, 3 ); | |
//Index children SKUs when indexing grouped products | |
function my_searchwp_extra_metadata( $extra_meta, $post_being_indexed ) { | |
if( 'product' == $post_being_indexed->post_type ){ | |
$child_skus = array(); | |
$children = get_post_meta( $post_being_indexed->ID, '_children', true ); | |
foreach( $children as $child ){ | |
$child_sku = get_post_meta( $child, '_sku', true ); | |
$child_skus[] = $child_sku; | |
} | |
$extra_meta['child_skus'] = implode( ',', $child_skus ); | |
} | |
return $extra_meta; | |
} | |
add_filter( 'searchwp_extra_metadata', 'my_searchwp_extra_metadata', 10, 2 ); | |
function my_searchwp_author_meta_keys( $keys ){ | |
// the keys we used to store author meta (see https://gist.github.com/jchristopher/8558947 for more info) | |
$my_child_skus = array( | |
'child_skus', | |
); | |
// merge my custom meta keys with the existing keys | |
$keys = array_merge( $keys, $my_child_skus ); | |
// make sure there aren't any duplicates | |
$keys = array_unique( $keys ); | |
return $keys; | |
} | |
add_filter( 'searchwp_custom_field_keys', 'my_searchwp_author_meta_keys', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment