Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active November 19, 2020 15:38
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 jchristopher/211bfb5d84d9a5bb2a1bf5489396a1dc to your computer and use it in GitHub Desktop.
Save jchristopher/211bfb5d84d9a5bb2a1bf5489396a1dc to your computer and use it in GitHub Desktop.
Index WooCommerce Product Variations with Products in SearchWP
<?php
// Add WooCommerce Product Variation data to parent Products in SearchWP.
add_filter( 'searchwp\entry\data', function( $data, \SearchWP\Entry $entry ) {
// If this is not a Product, there's nothing to do.
if ( 'product' !== get_post_type( $entry->get_id() ) ) {
return $data;
}
$my_extra_meta_key = 'searchwp_product_variations';
// Retrieve all Variations.
$product_variations = get_posts( [
'post_type' => 'product_variation',
'posts_per_page' => -1,
'post_parent' => $entry->get_id(),
] );
if ( empty( $product_variations ) ) {
return $data;
}
// Customize the data indexed for each Variation.
$data['meta'][ $my_extra_meta_key ] = array_filter( $product_variations, function( $variation ) {
$variation->searchwp_variation_data = [
'title' => get_the_title( $variation->ID ),
'content' => $variation->post_content,
'sku' => get_post_meta( $variation->ID, '_sku', true ),
];
return $variation;
} );
return $data;
}, 20, 2 );
// Add our Extra Meta entry to SearchWP's UI.
add_filter( 'searchwp\source\attribute\options\special', function( $keys, $args ) {
if ( $args['attribute'] !== 'meta' ) {
return $keys;
}
// This key is the same as the one used in the searchwp\entry\data hook above, they must be the same.
$my_extra_meta_key = 'searchwp_product_variations';
$option = new \SearchWP\Option( $my_extra_meta_key, 'Product Variations' );
// If there's already a match, remove it because we want ours there.
$keys = array_filter( $keys, function( $option ) use ( $my_extra_meta_key ) {
return $my_extra_meta_key !== $option->get_value();
} );
// Add "Product Variations" Option
$keys[] = $option;
return $keys;
}, 20, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment