Skip to content

Instantly share code, notes, and snippets.

@opicron
Last active October 20, 2022 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opicron/1ebfeb7c73729071e94d9a30996e4497 to your computer and use it in GitHub Desktop.
Save opicron/1ebfeb7c73729071e94d9a30996e4497 to your computer and use it in GitHub Desktop.
SearchWP custom search grouped/child #php #searchwp
<?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