0

this is my code for integrate product throught rest API.

Custom REST API endpoint for adding products to the WooCommerce cart.

Register the REST API route for adding to cart.

add_action('rest_api_init', function () {
    register_rest_route('theme/v1', '/add_to_cart', [
        'methods'             => 'POST',
        'callback'            => 'custom_add_to_cart_handler',
        'permission_callback' => '__return_true',
        /*'permission_callback' => function() {
            return is_user_logged_in();  // Ensure the user is logged in
        },*/
    ]);
});

function custom_add_to_cart_handler(WP_REST_Request $request) {
    // Ensure WooCommerce is loaded.
   if (!class_exists('WooCommerce') || !function_exists('WC')) {
        return new WP_Error('woocommerce_missing', 'WooCommerce is not initialized', ['status' => 500]);
    }
    
    // Initialize WooCommerce session if not active.
  if (!WC()->session) {
        WC()->initialize_session();  
  }

    // For logged-in users, ensure the customer object is properly set.
     if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        if (!WC()->customer || !WC()->customer->get_id()) {
            WC()->customer = new WC_Customer($user_id);
            // Optionally, set customer data (billing/shipping) if needed.
        }
    } else {
        // For guests, create a new WC_Customer instance.
        WC()->customer = new WC_Customer();  
    }

    // Ensure the WooCommerce cart is initialized.
    if (!WC()->cart) {
        wc_load_cart();
    }
        // Get existing cart items before adding new ones
    $existing_cart_items = WC()->cart->get_cart();

    // Retrieve JSON parameters.
    $params = $request->get_json_params();
    if (empty($params['items']) || !is_array($params['items'])) {
        return new WP_Error('no_items', 'No product items provided', ['status' => 400]);
    }

    $cart_results = [];

    // Process each item in the "items" array.
    foreach ($params['items'] as $item) {
        $product_id = isset($item['id']) ? intval($item['id']) : 0;
        $quantity   = isset($item['quantity']) ? intval($item['quantity']) : 1;
        $properties = isset($item['properties']) ? (array) $item['properties'] : [];

        if ($product_id > 0) {
            $product = wc_get_product($product_id);
            if (!$product) {
                $cart_results[] = [
                    'status'  => 'failed',
                    'message' => "Product ID {$product_id} does not exist",
                ];
                continue;
            }

            // Debug log: (Can be commented out in production)
            error_log("🛒 Adding product ID: $product_id, quantity: $quantity");

            // Check if product is already in the cart
          $cart_id = WC()->cart->generate_cart_id($product_id, 0, [], $properties);
            $cart_item_key = WC()->cart->find_product_in_cart($cart_id);
            
            if ($cart_item_key) {
                // If product exists, update its quantity.
                $existing_quantity = WC()->cart->get_cart_item($cart_item_key)['quantity'];
                WC()->cart->set_quantity($cart_item_key, $existing_quantity + $quantity);
                
            } else {
                 WC()->cart->add_to_cart($product_id, $quantity, 0, [], $properties);
            }

            $cart_results[] = [
                'status'     => 'success',
                'product_id' => $product_id,
                'message'    => 'Product added to cart successfully',
            ];
        }
    }

/**
 * Enqueue the custom add-to-cart JavaScript.
 */
function enqueue_custom_add_to_cart_script() {
    wp_enqueue_script(
        'custom-add-to-cart',
        get_stylesheet_directory_uri() . '/js/custom-add-to-cart.js',
        ['jquery'],
        '1.5',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_custom_add_to_cart_script');

issues : when i add woo-product and after add integrate product so thay replace the woo-product & only see the integrate product.

so is that any solution for this?

please help me.

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.