0
X
Add Snippet To Project
New Project
Add To Existing Project
<?php
/**
* Plugin Name: WP Turbo Add to Cart AJAX
* Description: Adds AJAX functionality to the add to cart button.
* Version: 1.0.0
* Author: WP Turbo
* Author URI: https://wpturbo.dev
* License: GPL v2 or later
* Text Domain: wpturbo
*/
// Enqueue JavaScript file for AJAX functionality
function wpturbo_enqueue_scripts() {
wp_enqueue_script(
'wpturbo-ajax-cart',
plugin_dir_url( __FILE__ ) . 'js/ajax-cart.js',
array( 'jquery' ),
'1.0.0',
true
);
wp_localize_script(
'wpturbo-ajax-cart',
'wpturbo_ajax_cart',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wpturbo_ajax_cart_nonce' )
)
);
}
add_action( 'wp_enqueue_scripts', 'wpturbo_enqueue_scripts' );
// AJAX Callback function to handle add to cart request
function wpturbo_ajax_add_to_cart() {
// Verify the AJAX request
check_ajax_referer( 'wpturbo_ajax_cart_nonce', 'security' );
// Get the product ID from the AJAX request
$product_id = intval( $_POST['product_id'] );
// Add the product to the cart
$cart_item_key = WC()->cart->add_to_cart( $product_id );
// Return the cart item key
if ( $cart_item_key ) {
echo $cart_item_key;
} else {
echo 'error';
}
wp_die();
}
add_action( 'wp_ajax_wpturbo_ajax_add_to_cart', 'wpturbo_ajax_add_to_cart' );
add_action( 'wp_ajax_nopriv_wpturbo_ajax_add_to_cart', 'wpturbo_ajax_add_to_cart' );
Explanation:
I made the following improvements to enhance the readability of the code:
These changes should make the code more readable and maintainable, improving its overall quality.