I want to add a custom checkbox during checkout for certain SKUs and/or one specific category. My code is already working for the SKUs I add or for Simple Products under category 571. However, it is not working for product variations of category 571. After doing some research this is because product variations don't inherit the attributes of their parent so when using $cart_item['data']->get_category_ids() it doesn't get anything because it's empty.
I found this post where it explains how to get the product category of its parent, I have implemented it into my code but I had no luck making it work. Here is my code so far:
add_action( 'woocommerce_review_order_before_submit', 'bt_add_checkout_checkbox', 10 );
/**
* Add WooCommerce additional Checkbox checkout field
*/
function bt_add_checkout_checkbox() {
//Check if wooCommerce is activated
if ( class_exists( 'WooCommerce' ) ) {
//Define SKUs you want to check for
$checkSKUs = ['SA300', 'SA1000', 'SA2000'];
//Grab all the SKUs in cart
$skus = array();
foreach( WC()->cart->get_cart() as $cart_item ) {
array_push($skus, $cart_item['data']->get_sku());
}
// Collect the category IDs.
$cat_ids = array();
foreach ( WC()->cart->get_cart() as $cart_item ) {
$cat_ids = array_merge(
$cat_ids, $cart_item['data']->get_category_ids()
);
}
// And here we check the IDs.
$cat_id = 571;
$count = count( $cat_ids );
if ( 1 === $count && in_array( $cat_id, $cat_ids ) ) {
$matchingCategory = 1;
} elseif ( $count && in_array( $cat_id, $cat_ids ) ) {
$matchingCategory = 2;
} else {
$matchingCategory = 0;
}
//check if product is variable
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item->is_type( 'variable' ) ) {
// Taxonomy for product categories
$taxonomy = 'product_cat';
// Get parent product categories
$parent_product_cats = get_terms( $taxonomy, array( 'parent' => 0, 'orderby' => 'slug', 'hide_empty' => false ) );
// Iterating through each parent categories (WP_Term Objects)
foreach ( $parent_product_cats as $product_cat_obj ) {
$term_id = $product_cat_obj->term_id; // term ID
if ( $term_id == 571 ) {
$matchingCategory = 1;
}
}
}
}
//Check if anything matches in both
$matchingResult = array_intersect($checkSKUs,$skus);
if (count($matchingResult) > 0 or $matchingCategory > 0) {
//If at least 1 SKU matches then generate checkout field
woocommerce_form_field( 'checkout_checkbox', array( // CSS ID
'type' => 'checkbox',
'class' => array('form-row mycheckbox'), // CSS Class
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true, // Mandatory or Optional
'label' => 'Custom label', // Label and Link
));
}
}
}
I am a newb when it comes to PHP so any information or documentation to help me out would be much appreciated. Thank you.