/* 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
}