仅当购物车包含类别时才显示WooCommerce结帐模板

问题描述:

我们有一个WooCommerce多步结帐。一个结账步骤是为了保险,但这种保险只适用于租赁类别。仅当购物车包含类别时才显示WooCommerce结帐模板

只看到保险步骤,如果出租产品在购物车中。发现了一个伟大的文章上Checking if the WooCommerce Cart Contains a Product Category但这些代码不会得到所要的结果,当我们把我们的ADD_ACTION片断加载结帐步骤:

enter image description here

这里是我们ADD_ACTION调用自定义模板(

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)); 
      } 

这里是它放置在代码内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)); 
      } 
} 

等都非常接近不知道什么C应该会出错。

感谢您的帮助, -L

+0

我还在[如何在WooCommerce中创建条件结账字段](https://wordimpress.com/create-conditional-checkout-fields-woocommerce/)上找到了这篇优秀的文章。 –

这做了修复。将$cat_check设置为false,运行购物车中的每个产品,检查购物车中是否有我们的类别slu((rentals),如果属实,我们就会发现并运行下一个if声明。

获取模板文件并在结帐订单信息(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'); 

希望能帮助别人。 **或者如果我的代码有任何问题,请告诉我。谢谢!