将产品添加到用户的ID WooCommerce

时间:2019-04-19 作者:Parth Shah

我制作了一个REST API,用于将用户的购物车项目同步到web视图和android视图。我用过CoCart WP plugin 以下是一些场景:

如果我从网站添加产品,我可以在两侧获取用户购物车项目(网站和android视图)如果我从android api添加产品,它不会显示在web视图中以下是我使用的详细信息-

https://co-cart.github.io/co-cart-docs/#add-to-cart

POST /wp-json/wc/v2/cart/add

curl -X POST https://example.com/wp-json/wc/v2/cart/add \\
    -H "Content-Type: application/json" \\
  -d \'{
    "product_id": 1722,
    "quantity": 1
  }\'
所以,我需要的解决方案,可以同步用户的购物车项目到网络视图到android。

我的想法是,是否可以通过特定用户的ID将产品添加到购物车?这让我的工作更轻松!!

1 个回复
最合适的回答,由SO网友:Pratik Patel 整理而成
/* Add to cart product api */
add_action( \'rest_api_init\', function () {
    register_rest_route( \'wp/v2\', \'add_to_cart_product\', array(
        \'methods\' => array(\'GET\',\'POST\'),
        \'callback\' => \'add_to_cart_product\',
    ) );
} );

function add_to_cart_product(){

    //wp_set_current_user($_POST[\'user_id\']);
    /*wp_set_auth_cookie($_POST[\'user_id\']);*/

    /* Required Parameters
    $_POST[\'user_id\']
    $_POST[\'product_id\'] */

    global $woocommerce,$wpdb;

    $array = $wpdb->get_results("select meta_value from ".$wpdb->prefix."usermeta where meta_key=\'_woocommerce_persistent_cart_1\' and user_id = ".$_POST[\'user_id\']);
    $data =$array[0]->meta_value;
    $cart_data=unserialize($data);

    $flag = 0;
    foreach($cart_data[\'cart\'] as $key => $val) {
        //$_product = $val[\'data\'];
        if($val[\'product_id\'] != $_POST[\'product_id\']){
            $flag = 0;
        }
        elseif($val[\'product_id\'] == $_POST[\'product_id\']) {
            $flag = 2;

        }
    }
    if($flag == 2){
        $cart_data[\'cart\'][$key][\'quantity\']++;
    }
    else{
        $string = $woocommerce->cart->generate_cart_id( $_POST[\'product_id\'], 0, array(), $cart_data[\'cart\'] );
        $product = wc_get_product( $_POST[\'product_id\'] );
        $cart_data[\'cart\'][$string] = array(
            \'key\' => $string,
            \'product_id\' => $_POST[\'product_id\'],
            \'variation_id\' => 0,
            \'variation\' => array(),
            \'quantity\' => 1,
            \'line_tax_data\' => array(
                \'subtotal\' => array(),
                \'total\' => array()
            ),
            \'line_subtotal\' => $product->get_price(),
            \'line_subtotal_tax\' => 0,
            \'line_total\' => $product->get_price(),
            \'line_tax\' => 0,
        );



    //echo "<pre>";
    //print_r($cart_data);
    //exit;
    //$serialize_data = serialize($cart_data);
    //$woocommerce->cart->add_to_cart( $_POST[\'product_id\'] );
    update_user_meta($_POST[\'user_id\'],\'_woocommerce_persistent_cart_1\',$cart_data);
    return cart_items(); // API response whatever you want
}