Reputation: 1674
I'm needing to display the available "Stock" for some variations. The catch is that I need to do it on a static, standard WP page. I know the Product ID and Variation ID, can I use those to get the variation stock count, outside of WooCommerce's templates? I'm fine with using PHP or AJAX, I have a custom page template applied to that page already.
Upvotes: 0
Views: 253
Reputation: 1674
This function can be called from any WordPress page, all you need to supply to the function is the main product ID, it must be a variable product and have variations setup to track inventory.
Makes the buttons
Checks how many are of that variation are in stock
shows a different button if the variation is sold out
function getVariationButtons($productID) {
$product = wc_get_product($productID);
$count_in_stock = 0;
if ( $product->is_type( 'variable' )) {
$variation_ids = $product->get_children(); // Get product variation IDs
foreach( $variation_ids as $variation_id ){
$variation = wc_get_product($variation_id);
$varname = $variation->get_attribute_summary();
$varid = $variation->get_variation_id();
$varqty = $variation->get_stock_quantity();
$varprice = $variation->get_price();
if ($varqty > 0) {
echo ' <a class="btn btn-primary" href="/cart/?add-to-cart='.$varid.'">'.$varname.' Pass $'.$varprice.' ('.$varqty.' left)</a>';
} else {
echo ' <a class="btn btn-default">'.$varname.' (Sold Out)</a>';
}
}
}
}
Upvotes: 1