2017-07-01 71 views
0

我知道,已經有一個現有的功能,您可以在訪問該網站時在購物車上添加某個產品。問題是你只能使用1個產品做到這一點,我希望它根據你訪問的頁面而變化。Woocommerce:訪問網頁時自動添加到購物車(變量產品ID)

這裏的現有代碼(加在functions.php文件)

add_action('template_redirect', 'add_product_to_cart'); 
function add_product_to_cart() { 
    if (! is_admin()) { 
     $product_id = 275; 
     $found = false; 
     //check if product already in cart 
     if (sizeof(WC()->cart->get_cart()) > 0) { 
      foreach (WC()->cart->get_cart() as $cart_item_key => $values) { 
       $_product = $values['data']; 
       if ($_product->id == $product_id) 
        $found = true; 
      } 
      // if product not found, add it 
      if (! $found) 
       WC()->cart->add_to_cart($product_id); 
     } else { 
      // if no products in cart, add it 
      WC()->cart->add_to_cart($product_id); 
     } 
    } 
} 

裏面我叫頁的template.php着陸頁,有這麼回聲選擇某種產品的ID的自定義字段。所以當我的用戶訪問這個頁面時,我想用這個ID替換functions.php文件上的$ product_id。我如何實現這一目標?

非常感謝您的幫助。

+0

你有沒有嘗試過的東西它不工作?這會更有幫助。 – Difster

+0

嗨。我在page-template.php中添加了一個全局變量,並將其傳遞給functions.php的product_id而不是「275」,但它不起作用 –

+0

如何將ID保存到cookie中,並在functions.php中檢索cookie。 – ucheng

回答

1

也許全局變量加載後的功能。而不是僅僅設置變量開始傳遞變量的函數,避免鉤:

中的functions.php

function add_product_to_cart($product_id) { 
    if (! is_admin()) { 
     $found = false; 
     //check if product already in cart 
     if (sizeof(WC()->cart->get_cart()) > 0) { 
      foreach (WC()->cart->get_cart() as $cart_item_key => $values) { 
       $_product = $values['data']; 
       if ($_product->id == $product_id) 
        $found = true; 
      } 
      // if product not found, add it 
      if (! $found) 
       WC()->cart->add_to_cart($product_id); 
     } else { 
      // if no products in cart, add it 
      WC()->cart->add_to_cart($product_id); 
     } 
    } 
} 
在頁面的template.php

add_product_to_cart(275); 
+0

嗨!感謝您的幫助。我嘗試了代碼,但出於某種原因,購物車返回空白。 –

+0

奇怪,但改變了第16行,以此以某種方式工作:WC() - > cart-> add_to_cart(275); –

+0

通過更改該行無論您傳遞給該函數的任何變量,它總是會添加ID爲275的產品 – buxbeatz

相關問題