Skip to content

Instantly share code, notes, and snippets.

@mircian
Created September 10, 2017 09:13
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 mircian/5fccfa245bcb85d5108a753c2d08e84f to your computer and use it in GitHub Desktop.
Save mircian/5fccfa245bcb85d5108a753c2d08e84f to your computer and use it in GitHub Desktop.
Add custom variation data to WooCommerce products in the SearchWP index. More details at https://mircian.com/2017/09/20/woocommerce-variation-data-searchwp/
<?php
/**
* @param array $extra_meta
* @param WP_Post $post_being_indexed
*
* @return array
*/
function m_index_woocommerce_variation_isbn( $extra_meta, $post_being_indexed ) {
// Bail fast if it's not the post type we're interested in.
if ( 'product' !== get_post_type( $post_being_indexed ) ) {
return $extra_meta;
}
// Retrieve product variations
$product_variations_args = array(
'post_type' => 'product_variation',
'posts_per_page' => 100, // If you have more than 100 variations for each product, change this.
'fields' => 'ids',
'post_parent' => $post_being_indexed->ID,
'suppress_filters' => false,
);
$product_variations = get_posts( $product_variations_args );
if ( ! empty( $product_variations ) ) {
// Store all codes as a Custom Field.
$extra_meta['m_product_isbns'] = array();
// Loop through all product variations, grab and store the ISBN.
foreach ( $product_variations as $product_variation ) {
$extra_meta['m_product_isbns'][] = get_post_meta( absint( $product_variation ), '_isbn_code', true ); // Use the relevant meta key.
}
}
// Make sure to return the newly found data.
return $extra_meta;
}
add_filter( 'searchwp_extra_metadata', 'm_index_woocommerce_variation_isbn', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment