2015-06-05 15 views
0

我正在構建一項訂閱服務,該服務每週自動將特定項目添加到用戶的購物車中,而無需登錄。問題是WooCommerce似乎在多個位置中攜帶購物車數據,我不確定哪個可以充當優先的「主」車。在用戶元中持有的持續購物車似乎是會話購物車數據的附屬品。但是,我無法弄清楚如何在沒有實際以用戶身份通過​​瀏覽器登錄的情況下獲取/設置會話購物車數據。是否有可能以編程方式更新用戶的購物車,只知道用戶ID?

我應該嘗試以某種方式欺騙用戶登錄以訪問會話變量嗎?或者有沒有辦法直接通過WooCommerce API來做到這一點?

+0

爲什麼不使用[WooCommerce Subscriptions](http://www.woothemes.com/products/woocommerce-subscriptions/)? – helgatheviking

+0

我其實正在使用它。我正在嘗試基於其掛鉤觸發一些購物車更新。該插件直接創建訂單完全繞過購物車。不過,我希望客戶可以選擇在自動完成之前更改訂單。 –

+0

我很確定訂閱不會繞過購物車。可能會有一項設置自動重定向到結賬,您可以禁用該項目,但項目仍會添加到購物車。你究竟想要做什麼? – helgatheviking

回答

0

因此,我發現會話數據是作爲選項元的網站選項存儲的,如果我將持久性購物車和會話設置爲同一事物,那麼它將始終加載適當的信息。下面是說明如何系列化做一個片段:

function add_products_programmatically($user_id) { 

    // Get the current session data and saved cart 
    $wc_session_data = get_option('_wc_session_'.$user_id); 

    // Get the persistent cart 
    $full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart', true); 

    // Create a new WC_Cart instance and add products programmatically 
    $cart = get_new_cart_with_products(); 

    // If there is a current session cart, overwrite it with the new cart 
    if($wc_session_data) { 
     $wc_session_data['cart'] = serialize($cart->cart_contents); 
     update_option('_wc_session_'.$user_id, $wc_session_data); 
    } 

    // Overwrite the persistent cart with the new cart data 
    $full_user_meta['cart'] = $cart->cart_contents; 
    update_user_meta($user_id, '_woocommerce_persistent_cart', $full_user_meta); 
} 

的get_new_cart_with_products()函數只是創建一個新的WC_Cart()對象,並添加項目,然後返回購物車對象。

相關問題