I have a WooCommerce store for makeup, and we need to make it so that variation names are searchable, since people will often be looking for a specific shade name. I'm using this bit of code to make the product variations searchable:
add_action( 'pre_get_posts', 'search_woocommerce_product_variations' );
function search_woocommerce_product_variations( $query ) {
if( ! is_admin() && is_search() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'page', 'product', 'product_variation' ) );
}
}
Edited to add: I've already tried adding this in, with no changes in the search results:
$query->set('post_status', array('publish'));
The problem is that when searching on the name of a variation it's pulling up products that do that have that search term in the variation name, but are currently set to Draft status. How can I prevent that from happening?
CodePudding user response:
Tell the query which post_status your looking for:
add_action( 'pre_get_posts', 'search_woocommerce_product_variations' );
function search_woocommerce_product_variations( $query ) {
if( ! is_admin() && is_search() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'page', 'product', 'product_variation' ) );
$query->set('post_status', array('publish'));
}
}
CodePudding user response:
<?php
$args = array(
'post_type' => 'product',
'numberposts' => -1,
);
$products = get_posts( $args );
foreach($products as $product):
$product_s = wc_get_product( $product->ID );
if ($product_s->product_type == 'variable') {
$args = array(
'post_parent' => $plan->ID,
'post_type' => 'product_variation',
'numberposts' => -1,
);
$variations = $product_s->get_available_variations();
echo '<pre>';
print_r($variations);
echo '</pre>';
}
endforeach;
?>