-
-
Save anonymous/1af5ca94dcf38634a4c2a8cd41ef5b6a to your computer and use it in GitHub Desktop.
Hide product parent if variation is out stock
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 | |
function tm_remove_product_stock_region($query) { | |
$product_variable = new WC_Product_Variable(); | |
$product_variations = $product_variable->get_available_variations(); | |
// /** Get users region. */ | |
$user_region = tm_get_user_region(); | |
$post__in = array(); | |
foreach ( $product_variations as $variation ) { | |
/** Get products regions. */ | |
$product_region = $variation['attributes']['attribute_pa_regions']; | |
if ($user_region === $product_region && !$variation->is_in_stock()) { | |
$post__in[] = $variation['product_id']; | |
add_filter('woocommerce_product_is_visible', function($is_visible, $id) { | |
$is_visible = false; | |
return $is_visible; | |
}, 10,2); | |
} else if ($user_region === $product_region && $variation->is_in_stock()) { | |
$post__in[] = $variation['product_id']; | |
add_filter('woocommerce_product_is_visible', function($is_visible, $id) { | |
$is_visible = true; | |
return $is_visible; | |
}, 10,2); | |
} | |
} | |
if(is_array($post__in) && $post__in != null){ | |
$query->set('post__in', $post__in); | |
} | |
return $query; | |
} | |
add_action('pre_get_posts', 'tm_remove_product_stock_region', 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment