I am trying to set a variation's maximum quantity allowance based on the value of a one of its custom fields.
Everything is good - the code is working below, however rather than $quantity = round(9/3);
I want the value to be $quantity = round($quantity/$weight);
The issue I am having (and have had numerous times in the past with other functions) is that I can't for the life of me seem to pull the correct 'Custom_Field'
data. Everything I try returns either boolean false
or string Length(0)
. When I do a var_dump($variation_ID)
I get a ton of data, but my custom field is not there.
This is strange, because the data is pulled in other functions I have - but not in this situation and I can't figure out why.
// On single product pages
add_filter( 'woocommerce_available_variation', 'customizing_available_variation', 10, 3 );
function customizing_available_variation( $args, $product_id, $variation_id ) {
$product = wc_get_product ( $product_id );
$weight = get_post_meta( $variation_ID, 'custom_field', true );
$product_stock = $product_id->get_stock_quantity();
var_dump($variation_id);
$quantity = round(9/3);
if( is_woocommerce() ){
$args['max_qty'] = $quantity;
}
return $args;
}
woocommerce_available_variation
passes three arguments, the third one being a WC_Product_Variation
(that's why you're getting a ton of data when var_dump
-ing it).
You've named your third argument $variation_id
, which probably led you to treating it as a post/product id.
Meaning, you're trying to pass a WC_Product_Variation
as an id to get_post_meta()
:
$weight = get_post_meta( $variation_ID, 'custom_field', true );
You're also doing the same thing for the second argument (which is the product, not the product id).
You just have to get the variation id and pass that instead:
/**
* Customize available variation
*
* @param array $args
* @param WC_Product_Variable $product
* @param WC_Product_Variation $variation
*/
function customizing_available_variation( $args, $product, $variation ) {
$weight = get_post_meta( $variation->get_id(), 'custom_field', true );
// …
}