// بارگذاری اسکریپت JS اختصاصی + دادههای Ajax
add_action('wp_enqueue_scripts', 'custom_ajax_cart_scripts');
function custom_ajax_cart_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('custom-cart-script', get_stylesheet_directory_uri() . '/js/custom-cart.js', array('jquery'), null, true);
wp_localize_script('custom-cart-script', 'wc_add_to_cart_params', array(
'ajax_url' => admin_url('admin-ajax.php')
));
}
// Ajax افزودن به سبد خرید
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'handle_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'handle_ajax_add_to_cart');
function handle_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$product_status = get_post_status($product_id);
if (WC()->cart->add_to_cart($product_id, $quantity) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
WC_AJAX::get_refreshed_fragments(); // آپدیت سبد
} else {
wp_send_json_error(array('error' => true, 'product_url' => get_permalink($product_id)));
}
wp_die();
}
// Ajax حذف از سبد خرید
add_action('wp_ajax_remove_from_cart', 'handle_remove_from_cart');
add_action('wp_ajax_nopriv_remove_from_cart', 'handle_remove_from_cart');
function handle_remove_from_cart() {
if (!isset($_POST['product_id'])) {
wp_send_json_error('Missing product ID');
wp_die();
}
foreach (WC()->cart->get_cart() as $cart_item_key => $item) {
if ($item['product_id'] == $_POST['product_id']) {
WC()->cart->remove_cart_item($cart_item_key);
break;
}
}
WC_AJAX::get_refreshed_fragments(); // سبد بالا آپدیت بشه
wp_die();
}
Warning: Cannot modify header information - headers already sent by (output started at /home3/tavalod4/public_html/wp-content/themes/astra-child/functions.php:1) in /home3/tavalod4/public_html/wp-includes/pluggable.php on line 1450
Warning: Cannot modify header information - headers already sent by (output started at /home3/tavalod4/public_html/wp-content/themes/astra-child/functions.php:1) in /home3/tavalod4/public_html/wp-includes/pluggable.php on line 1453