Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugin-republic/6348efc3fd9cf582c42e7745a7ee1f8a to your computer and use it in GitHub Desktop.
Save plugin-republic/6348efc3fd9cf582c42e7745a7ee1f8a to your computer and use it in GitHub Desktop.
<?php
/**
* Custom validation for add-on fields
*/
function prefix_validate_total_child_items( $passed, $product_id, $quantity, $variation_id=null, $cart_item_data=array() ) {
// The parent product ID that we need to validate
$parent_product_ID = 9059; // Change this
if( $parent_product_ID != $product_id ) {
return $passed;
}
// The list of field IDs that need to be checked
$fields = array( 9061 ); // Change this
// The combined quantity
$total = 0;
// The required quantity
$required = 15; // Change this
// Iterate through each field and get combined quantity
$groups = pewc_get_extra_fields( $product_id );
if( $groups ) {
foreach( $groups as $group_id=>$group ) {
if( isset( $group['items'] ) ) {
foreach( $group['items'] as $field_id=>$field ) {
$id = $field['id'];
if( in_array( $field_id, $fields ) ) {
// This is one of our fields
$child_products = ! empty( $field['child_products'] ) ? $field['child_products'] : array();
foreach( $child_products as $key=>$child_product_id ) {
if( isset( $_POST[$id . '_child_quantity_' . $child_product_id] ) ) {
$total += $_POST[$id . '_child_quantity_' . $child_product_id];
}
}
}
}
}
}
}
if( $total < $required ) {
wc_add_notice( 'My validation message', 'error' ); // Change this
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'prefix_validate_total_child_items', 10, 5 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment