Advertisement
hmbashar

Ajax Action function

Jan 2nd, 2024 (edited)
872
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | None | 0 0
  1. function abcbiz_ajax_add_to_cart_handler() {
  2.  
  3.     if (!isset($_POST['abcbiz_cart_nonce']) || !wp_verify_nonce($_POST['abcbiz_cart_nonce'], 'abcbiz_add_to_cart_nonce')) {
  4.         wp_send_json_error(['message' => 'Nonce verification failed.']);
  5.         return;
  6.     }
  7.  
  8.     if (!isset($_POST['product_id'])) {
  9.         wp_send_json_error(['message' => 'Product ID is missing.']);
  10.         return;
  11.     }
  12.  
  13.     $product_id = (int) $_POST['product_id'];
  14.     $quantity = isset($_POST['quantity']) ? (int) $_POST['quantity'] : 1; // Use sent quantity or default to 1
  15.  
  16.     if (!wc_get_product($product_id)) {
  17.         wp_send_json_error(['message' => 'Invalid product.']);
  18.         return;
  19.     }
  20.  
  21.     $cart_item_key = WC()->cart->add_to_cart($product_id, $quantity);
  22.  
  23.     if ($cart_item_key) {
  24.         wp_send_json_success(['message' => 'Product successfully added to cart.']);
  25.     } else {
  26.         wp_send_json_error(['message' => 'Failed to add the product to the cart.']);
  27.     }
  28. }
  29. add_action('wp_ajax_abcbiz_ajax_add_to_cart_handler', 'abcbiz_ajax_add_to_cart_handler');
  30. 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