2017-06-21 61 views
0

我們有一個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/)上找到了這篇優秀的文章。 –

回答

0

這做了修復。將$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'); 

希望能幫助別人。 **或者如果我的代碼有任何問題,請告訴我。謝謝!

相關問題