Rest API to store products in cart based on the user id in woocommerce

前端 未结 1 1482
别那么骄傲
别那么骄傲 2021-01-28 18:28

Only related reference for the same I found with accepted by few people is the below mentioned code but there is no session stored in options table with the following key \'_wc_

相关标签:
1条回答
  • 2021-01-28 19:10

    After a lot of research to the way woo-commerce uses persistent cart I have created a working solution.

    function woocomm_add_to_cart($param) {
    
    global $wpdb;
    $user_id = $param['user_id'];
    $objProduct = new WC_Session_Handler();
    
    $wc_session_data = $objProduct->get_session($user_id);
    
    // Get the persistent cart may be _woocommerce_persistent_cart can be in your case check in user_meta table
    $full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart_1',true);
    
    // create new Cart Object
    $cartObj = new WC_Cart();
    
    // Add old cart data to newly created cart object
    if($full_user_meta['cart']) {
        foreach($full_user_meta['cart'] as $sinle_user_meta) {
            $cartObj->add_to_cart( $sinle_user_meta['product_id'], $sinle_user_meta['quantity']  );
        }
    }
    
    // Add product and quantities coming in request to the new cart object
    if($param['products']){
        foreach($param['products'] as $prod) {
            $cartObj->add_to_cart( $prod['product_id'], $prod['quantity']  );
        }
    }
    
    $updatedCart = [];
    foreach($cartObj->cart_contents as $key => $val) {
        unset($val['data']);
        $updatedCart[$key] = $val;
    }
    
    // If there is a current session cart, overwrite it with the new cart
    if($wc_session_data) {
        $wc_session_data['cart'] = serialize($updatedCart);
        $serializedObj = maybe_serialize($wc_session_data);
    
    
        $table_name = 'wp_woocommerce_sessions';
    
        // Update the wp_session table with updated cart data
        $sql ="UPDATE $table_name SET 'session_value'= '".$serializedObj."', WHERE  'session_key' = '".$user_id."'";
    
        // Execute the query
        $rez = $wpdb->query($sql);
    }
    
    // Overwrite the persistent cart with the new cart data
    $full_user_meta['cart'] = $updatedCart;
    update_user_meta($user_id, '_woocommerce_persistent_cart_1', $full_user_meta);
    
    $response = [
        'status' => true,
        'message' => 'Products successfully added to cart'
    ];
    
    return rest_ensure_response($response);
    
    
    }
    

    Here is the Request json data for the Rest API:

    {"user_id": 15, "products" : [{"product_id":"81","quantity":"0.5"},{"product_id":"1817","quantity":"0.5"}]}
    
    0 讨论(0)
提交回复
热议问题