![](/img/trans.png)
[英]Disable ajax for add to cart button in single product page / Wordpress / Woocommerce
[英]Woocommerce - Product Page - How to create AJAX on "Add To Cart" button?
我想在可以使用 AJAX 的產品頁面上制作一個“添加到購物車”按鈕。 我該怎么做? 當我在產品頁面上添加到購物車時 - 它會刷新頁面,我如何通過 AJAX 使其工作?
存檔中“快速查看”上的“添加到購物車”按鈕由 ajax 工作 - 這很棒,但我如何在產品頁面上做同樣的事情?
我想單擊產品頁面上的“帶我回家”,然后通過 ajax 將具有選定屬性的產品添加到我的購物車,並打開該購物車(就像當您將鼠標懸停在菜單上的袋子圖像上時)並搖晃袋子圖片。
我們可以從存檔頁面使用ajax。 這很簡單 -
刪除提交表單的舊按鈕:
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
將 ajax-link 從存檔頁面添加到單個產品頁面:
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30 );
PS JS 回調。 例如,您可以顯示帶有“返回商店”和“購物車”或“結帳”鏈接的彈出窗口
$('body').on('added_to_cart',function(){
// Callback -> product added
//$('.popup').show();
});
只需將以下屬性添加到 Add to Cart 按鈕即可啟用 Ajax 按鈕。
<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" aria-label="Add “<?php the_title_attribute() ?>” to your cart"> Add to Cart </a>
ajax_add_to_cart add_to_cart_button
類和data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>"
屬性是必需的。
無需應用任何操作或過濾器。
請先閱讀此頁面:
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
首先你需要在你的functions.php中添加一些代碼,例如:
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
$product_id = intval( $_POST['product_id'] );
// add code the add the product to your cart
die();
}
然后,您必須添加一些 javascript 代碼來觸發添加到購物車並調用該函數:
jQuery( ".add-to-cart" ).each(function()
{
var product_id = jQuery(this).attr('rel');
var el = jQuery(this);
el.click(function() {
var data = {
action: 'add_foobar',
product_id: product_id
};
jQuery.post('/wp-admin/admin-ajax.php' , data, function(response) {
if(response != 0) {
// do something
} else {
// do something else
}
});
return false;
});
});
這只是如何做到這一點的一個例子。 雖然它非常基礎。 這個 javascript 檢查類名 .add-to-cart 的鏈接,並檢查相應產品的 rel 屬性。 然后它將產品 id 發送到 php 類。 在那里您需要添加代碼以將相應的產品添加到購物車。
我建議您搜索有關該主題的更多信息,以使其適合您的需求。 祝你好運。
Woocommerce 已經出現了。 我認為現在解決方案很簡單。 如果我遺漏了一些東西,只需檢查“在檔案中啟用 AJAX 添加到購物車按鈕”並使用woocommerce_template_loop_add_to_cart()
函數。
復選框選項位於 Woocommerce > 設置 > 產品 > 常規下。
然后只需在您希望輸出按鈕的地方使用woocommerce_template_loop_add_to_cart()即可。
如果您像我一樣使用自定義循環,您需要確保將產品設為全局,以便woocommerce_template_loop_add_to_cart()
工作。
下面是一個使用該函數的小例子:
add_shortcode( 'buy_again' , 'msp_buy_again_shortcode' );
function msp_buy_again_shortcode(){
$order_items = msp_get_customer_unique_order_items( get_current_user_id() );
echo '<div class="owl-carousel owl-theme">';
foreach( $order_items as $id ){
$product = wc_get_product( $id );
global $product;
if( ! empty( $product ) ){
?>
<div class="card buy-again-product">
<a class="link-normal" href="<?php echo $product->get_permalink(); ?>">
<?php echo $product->get_image( 'woocommerce_thumbnail', array( 'class' => 'card-img-top' ) ) ?>
<div class="card-body">
<?php echo wc_get_rating_html( $product->get_average_rating(), $product->get_review_count() ) ?>
<h5><?php echo $product->get_name(); ?></h5>
<p><?php echo $product->get_price_html() ?></p>
<?php woocommerce_template_loop_add_to_cart(); ?>
</div>
</a>
</div>
<?php
}
}
// loop and display buy again.
// try to use the official woocommerce loop.
echo '</div>';
}
將此代碼復制到您的文件中。 例如: my-theme-wc-single-ajax-add-cart.js 。
function myThemeWc_SingleProductAddToCart(thisObj) {
if (typeof($) === 'undefined') {
var $ = jQuery.noConflict();
}
var thisForm = thisObj.closest('form');
var button = thisForm.find('.button');
var formUrl = thisForm.attr('action');
var formMethod = thisForm.attr('method');
if (typeof(formMethod) === 'undefined' || formMethod == '') {
formMethod = 'POST';
}
var formData = new FormData(thisForm[0]);
formData.append(button.attr('name'), button.val());
button.removeClass('added');
button.addClass('loading');
myThemeWc_SingleProductCartAjaxTask = $.ajax({
url: formUrl,
method: formMethod,
data: formData,
cache: false,
contentType: false,
processData: false
})
.done(function(data, textStatus, jqXHR) {
$(document.body).trigger('wc_fragment_refresh');
$.when(myThemeWc_SingleProductCartAjaxTask)
.then(myThemeWc_SingleProductUpdateCartWidget)
.done(function() {
button.removeClass('loading');
button.addClass('added');
setTimeout(function() {
button.removeClass('added');
}, 2000);
});
})
.fail(function(jqXHR, textStatus, errorThrown) {
button.removeClass('loading');
})
.always(function(jqXHR, textStatus, errorThrown) {
$('.cart').off('submit');
myThemeWc_SingleProductListenAddToCart();
});
}// myThemeWc_SingleProductAddToCart
function myThemeWc_SingleProductListenAddToCart() {
if (typeof($) === 'undefined') {
var $ = jQuery.noConflict();
}
$('.cart').on('submit', function(e) {
e.preventDefault();
myThemeWc_SingleProductAddToCart($(this));
});
}// myThemeWc_SingleProductListenAddToCart
/**
* Update WooCommerce cart widget by called the trigger and listen to the event.
*
* @returns {undefined}
*/
function myThemeWc_SingleProductUpdateCartWidget() {
if (typeof($) === 'undefined') {
var $ = jQuery.noConflict();
}
var deferred = $.Deferred();
$(document.body).on('wc_fragments_refreshed', function() {
deferred.resolve();
});
return deferred.promise();
}// myThemeWc_SingleProductUpdateCartWidget
var myThemeWc_SingleProductCartAjaxTask;
// on page load --------------------------------------------
jQuery(function($) {
$(document.body).on('wc_fragments_refreshed', function() {
console.log('woocommerce event fired: wc_fragments_refreshed');
});
myThemeWc_SingleProductListenAddToCart();
});
您可能需要將函數、變量前綴myThemeWc_
為您想要的。
此代碼使用原始的 WooCommerce 單個產品頁面添加到購物車按鈕但停止其功能,然后使用 ajax 代替保留表單中的所有值。
然后將這個js文件入隊。
add_action('wp_enqueue_scripts', 'mythemewc_enqueue_scripts');
function mythemewc_enqueue_scripts() {
if (class_exists('\\WooCommerce') && is_product()) {
wp_enqueue_script('mythemewc-single-product', trailingslashit(get_stylesheet_directory_uri()) . 'assets/js/my-theme-wc-single-ajax-add-cart.js', ['jquery'], false, true);
}
}
您可能需要對 css 按鈕進行編碼以使其顯示加載的添加圖標。
這里是css。
.woocommerce #respond input#submit.added::after,
.woocommerce a.btn.added::after,
.woocommerce button.btn.added::after,
.woocommerce input.btn.added::after,
.woocommerce .single_add_to_cart_button.added::after {
font-family: WooCommerce;
content: '\e017';
margin-left: .53em;
vertical-align: bottom;
}
.woocommerce #respond input#submit.loading,
.woocommerce a.btn.loading,
.woocommerce button.btn.loading,
.woocommerce input.btn.loading,
.woocommerce .single_add_to_cart_button.loading {
opacity: .25;
padding-right: 2.618em;
position: relative;
}
.woocommerce #respond input#submit.loading::after,
.woocommerce a.btn.loading::after,
.woocommerce button.btn.loading::after,
.woocommerce input.btn.loading::after,
.woocommerce .single_add_to_cart_button.loading::after {
font-family: WooCommerce;
content: '\e01c';
vertical-align: top;
font-weight: 400;
position: absolute;
right: 1em;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
}
信息:使用 WooCommerce 2.4.10 測試。
嗯,我用另一種方式做到了,使用了從添加到購物車的 woocommerce 循環(woocommerce/templates/loop/add-to-cart.php)
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
但問題是它只添加了 1 個數量,事實上,您可以在列出數量的代碼中看到:1,所以我遇到了問題,直到我遇到了救我的人
附: 留下第一部分,它只為購物車中不需要超過 1 個產品的人添加 1 個產品,但我為那些需要將超過 1 個產品添加到購物車的人添加了一個解決方案。
您可以在單個產品中復制存檔按鈕的行為
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); function woocommerce_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']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_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']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
你可以在這里看到完整的教程
https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/
添加到購物車.js
jQuery( document ).on( 'click', '.product_type_simple', function() {
var post_id = jQuery(this).data('product_id');//store product id in post id variable
var qty = jQuery(this).data('quantity');//store quantity in qty variable
jQuery.ajax({
url : addtocart.ajax_url, //ajax object of localization
type : 'post', //post method to access data
data :
{
action : 'prefix_ajax_add_foobar', //action on prefix_ajax_add_foobar function
post_id : post_id,
quantity: qty
},
success : function(response){
jQuery('.site-header .quantity').html(response.qty);//get quantity
jQuery('.site-header .total').html(response.total);//get total
//loaderContainer.remove();
alert("Product Added successfully..");
}
});
return false;
});
要使 ajax woocomerce 在另一個頁面上工作,您將需要。 進入functions.php
粘貼這個:
remove_action ('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
add_action ('woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30);
在footer.php最后粘貼這個:
<script>
$ ('body'). on ('add_to_cart', function () {
// Callback -> product added
// $ ('. popup'). show ();
});
</script>
我在后端部分使用了這個插件https://wordpress.org/plugins/woo-ajax-add-to-cart/
我沒有使用產品頁面,所以我修改了腳本以使用任何按鈕:
(function($) { $(document).on('click', '.btn', function(e) { var $thisbutton = $(this); try { var href = $thisbutton.prop('href').split('?')[1]; if (href.indexOf('add-to-cart') === -1) return; } catch (err) { return; } e.preventDefault(); var product_id = href.split('=')[1]; var data = { product_id: product_id }; $(document.body).trigger('adding_to_cart', [$thisbutton, data]); $.ajax({ type: 'post', url: wc_add_to_cart_params.wc_ajax_url.replace( '%%endpoint%%', 'add_to_cart' ), data: data, beforeSend: function(response) { $thisbutton.removeClass('added').addClass('loading'); }, complete: function(response) { $thisbutton.addClass('added').removeClass('loading'); }, success: function(response) { if (response.error & response.product_url) { window.location = response.product_url; return; } else { $(document.body).trigger('added_to_cart', [ response.fragments, response.cart_hash ]); $('a[data-notification-link="cart-overview"]').click(); } } }); return false; }); })(jQuery);
對我來說工作出色。 我認為這是使用 Ajax 的最簡單的解決方案。
<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button add-cart" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>"> + Add to cart</a>
我使用了Eh Jewel 的答案,但隨后添加了一些自定義 JS,以便將產品添加到購物車中。 這完成了能夠以任何方式更新頁面的最終 AJAX 過程。
為了完整起見,這是我使用的 HTML 代碼(與Eh Jewel 的相同):
<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" aria-label="Add “<?php the_title_attribute() ?>” to your cart"> Add to Cart </a>
然后對於自定義 JS 位:
$(window).on('load', function() {
$('body').on( 'added_to_cart', function( button, data ){
// Put custom functionality here. Debugging below shows you what you have to work with:
console.log('added_to_cart');
console.log(button);
console.log(data);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.