I'm still quite new to writing functions and PHP so please excuse me if this is easy. Let me provide a little background...
I have built an e-commerce site using MarketPress by WPMUDev and trying to write a function that will show the stock remaining depending on the product variation selected.
In MarketPress, if you have more than one variation of a product, e.g. Shirt (Blue/Black/White) then you specify the one product with three variations. On the single product page, you have a drop down box for each variant.
The code I have so far will find the stock level of the initial product only and not the variants. Please see below:
function mp_product_stock_sc( $atts ){
global $post;
$product_id = $post->ID;
$stock = get_post_meta($product_id, 'mp_inventory', true);
$high_st = 1;
//return 'Default Stock: ' . $stock[0];
if ($stock[0] <= $high_st AND $stock[0] > 0 ) {
//return 'Hurry! We only have ' . $stock[0] . ' in stock!';
return 'Hurry! Only one left in stock!';
} elseif ($stock[0] == 0) {
return '';
} else {
return 'In Stock';
}
return 'Stock: ' . $stock[0];
}
add_shortcode( 'mp_product_stock', 'mp_product_stock_sc' );
I know that the function is selecting the first variant in $stock[0] because the [0] is explicitly defined. By manually writing [1] it would select the next variant and so on.
What I need to do is, on the product variation drop down list, for each variant to have next to it the stock, e.g:
Shirt (Blue) - In Stock
Shirt (Black) - Hurry only 1 left!
Shirt (White) - In Stock
I know where to put the code, just not how to return the value.
Any advice greatly appreciated. There's probably a much better way of writing this too...
Thanks!
Edit: Adding below the code where the drop down is generated.
//create select list if more than one variation
if (is_array($meta["mp_price"]) && count($meta["mp_price"]) > 1 && empty($meta["mp_file"])) {
$variation_select = '<select class="mp_product_variations" name="variation">';
foreach ($meta["mp_price"] as $key => $value) {
$disabled = (in_array($key, $no_inventory)) ? ' disabled="disabled"' : '';
$variation_select .= '<option value="' . $key . '"' . $disabled . '>' . esc_html($meta["mp_var_name"][$key]) . ' - ';
if ($meta["mp_is_sale"] && $meta["mp_sale_price"][$key]) {
$variation_select .= $mp->format_currency('', $meta["mp_sale_price"][$key]);
} else {
$variation_select .= $mp->format_currency('', $value);
}
$variation_select .= "</option>
";
}
$variation_select .= "</select>
";
} else {
$button .= '<input type="hidden" name="variation" value="0" />';
}