Created
September 10, 2017 09:13
-
-
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/
This file contains 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 | |
/** | |
* @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