Reputation: 31
We have a WooCommerce Multi-step checkout. One checkout step is for insurance, but this insurance is only for the rental category.
Looking to only show the insurance step if a rental product is in the cart. Found a great article on Checking if the WooCommerce Cart Contains a Product Category but the code is not giving the desired result when we place our add_action snippet to load the checkout step:
Here is our add_action call for the custom template (
add_action('woocommerce_multistep_checkout_after_shipping', 'add_my_insurance_step_with_new_field');
function add_my_insurance_step_with_new_field( $checkout ) {
wc_get_template( 'checkout/insurance.php', array( 'checkout' => $checkout ) );
}
And here is it placed within the code from SkyVerge:
// set our flag to be false until we find a product in that category
$cat_check = false;
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// replace 'membership' with your category's slug
if ( has_term( 'rentals', 'product_cat', $product->id ) ) {
$cat_check = true;
// break because we only need one "true" to matter here
break;
}
}
// if a product in the cart is in our category, do something
if ( $cat_check ) {
// we have the category, do what we want
add_action('woocommerce_multistep_checkout_after_shipping', 'add_my_insurance_step_with_new_field');
function add_my_insurance_step_with_new_field( $checkout ) {
wc_get_template( 'checkout/insurance.php', array( 'checkout' => $checkout ) );
}
}
So very close! Not sure what could be going wrong.
Thanks for your help, -L
Upvotes: 1
Views: 559
Reputation: 31
This did the fix. Set $cat_check
to false
, run through each product in the cart, check if it has our category slug (rentals
) in the cart, if true we break out and run the next if
statement.
Which gets the template file and loads it before checkout order info (woocommerce_multistep_checkout_before_order_info
).
function cclever_show_insurance_step_if_rentals() {
if ( function_exists( 'wc_checkout_add_ons' ) ) {
// set to false first
$cat_check = false;
// check each cart item for our category
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
// replace 'rentals' with your category's slug
if ( has_term( 'rentals', 'product_cat', $product->id ) ) {
$cat_check = true;
// we only need one "true" to leave
break;
}
}
// if a product in the cart is in our category, remove the add-ons
if ( $cat_check ) {
add_action('woocommerce_multistep_checkout_before_order_info', 'cclever_add_insurance_custom_step');
function cclever_add_insurance_custom_step( $checkout ) {
wc_get_template( 'checkout/insurance.php', array( 'checkout' => $checkout ) );
}
}
}
}
add_action( 'woocommerce_before_checkout_form', 'cclever_show_insurance_step_if_rentals' );
Hope that helps someone out. ** or if there is anything wrong with my code, please let me know. Thanks!
Upvotes: 1