Как я уже упоминал ранее, использование $_REQUEST
не обязательно.
В приведенном ниже коде я установил $weight = 40
; в целях тестирования. Предполагая, что ваш get_post_meta
правильный? а числовое значение?
function validate_attribute_weight( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Get custom field
$weight = get_post_meta( $variation_id, 'custom_field', true );
// FOR TESTING PURPOSES, DELETE AFTERWORDS!!!
$weight = 40;
// FOR TESTING PURPOSES, DELETE AFTERWORDS!!!
if ( ! empty( $weight ) ) {
// Get product object
$product = wc_get_product( $product_id );
// Get current product stock
$product_stock = $product->get_stock_quantity();
// ( Weight * quantity ) > product stock
if( ( ( $weight * $quantity ) > $product_stock ) ) {
wc_add_notice( sprintf( 'You cannot add that amount of %1$s to the cart because there is not enough stock (%2$s remaining).', $product->get_name(), $product_stock ), 'error' );
$passed = false;
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'validate_attribute_weight', 10, 5 );