Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function abcbiz_ajax_add_to_cart_handler() {
- if (!isset($_POST['abcbiz_cart_nonce']) || !wp_verify_nonce($_POST['abcbiz_cart_nonce'], 'abcbiz_add_to_cart_nonce')) {
- wp_send_json_error(['message' => 'Nonce verification failed.']);
- return;
- }
- if (!isset($_POST['product_id'])) {
- wp_send_json_error(['message' => 'Product ID is missing.']);
- return;
- }
- $product_id = (int) $_POST['product_id'];
- $quantity = isset($_POST['quantity']) ? (int) $_POST['quantity'] : 1; // Use sent quantity or default to 1
- if (!wc_get_product($product_id)) {
- wp_send_json_error(['message' => 'Invalid product.']);
- return;
- }
- $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity);
- if ($cart_item_key) {
- wp_send_json_success(['message' => 'Product successfully added to cart.']);
- } else {
- wp_send_json_error(['message' => 'Failed to add the product to the cart.']);
- }
- }
- add_action('wp_ajax_abcbiz_ajax_add_to_cart_handler', 'abcbiz_ajax_add_to_cart_handler');
- add_action('wp_ajax_nopriv_abcbiz_ajax_add_to_cart_handler', 'abcbiz_ajax_add_to_cart_handler');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement