Php Woocommerce-产品页面-如何在“上创建AJAX”;“添加到购物车”;按钮

Php Woocommerce-产品页面-如何在“上创建AJAX”;“添加到购物车”;按钮,php,ajax,wordpress,woocommerce,Php,Ajax,Wordpress,Woocommerce,我想在产品页面上创建一个“添加到购物车”按钮,该按钮可以使用AJAX。我怎么做?当我在产品页面上添加到购物车时,它会刷新页面,如何通过AJAX使其工作 ajax在归档文件的“快速查看”上的“添加到购物车”按钮起作用——这很好,但我如何在产品页面上做到这一点呢 我想点击产品页面上的“带我回家”,然后 通过ajax将具有所选属性的产品添加到我的购物车中,并将打开购物车(如将鼠标悬停在菜单上的行李图像上),然后晃动行李图像。请阅读以下页面: 首先,您需要向functions.php添加一些代码,例如

我想在产品页面上创建一个“添加到购物车”按钮,该按钮可以使用AJAX。我怎么做?当我在产品页面上添加到购物车时,它会刷新页面,如何通过AJAX使其工作

ajax在归档文件的“快速查看”上的“添加到购物车”按钮起作用——这很好,但我如何在产品页面上做到这一点呢

我想点击产品页面上的“带我回家”,然后
通过ajax将具有所选属性的产品添加到我的购物车中,并将打开购物车(如将鼠标悬停在菜单上的行李图像上),然后晃动行李图像。

请阅读以下页面:

首先,您需要向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检查具有classname.add-to-cart的链接,并检查相应产品的rel属性。然后将产品id发送到php类。在那里,您需要添加代码以将相应的产品添加到购物车


我建议你搜索更多关于这个主题的信息,使之适合你的需要。祝你好运。

我们可以从归档页面使用ajax。很简单-

删除提交表单的旧按钮:

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
将ajax链接从归档页面添加到单个产品页面:

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30 );
p.S.JS回调。例如,您可以显示带有“返回商店”和“购物车”或“结帐”链接的弹出窗口


信息:使用WooCommerce 2.4.10进行测试

嗯,我用了另一种方法,使用了从add到cart的woocommerce循环(woocommerce/templates/loop/add到cart.php)

global$产品;
回显应用过滤器('woocommerce\u loop\u add\u to\u cart\u link',
sprintf(“”,
esc_url($product->add_to_cart_url()),
esc_attr($product->id),
esc_attr($product->get_sku()),
esc_属性(isset($数量)?$数量:1),
$product->is_purchable()&&&$product->is_in_stock()?“添加到购物车按钮”:“,
esc_attr($product->product_type),
esc_html($product->add_to_cart_text())
),
$product);
但是问题是它只添加了1个数量,事实上,您可以在代码中看到列出的数量:1,所以我遇到了问题,直到我遇到

另外,在第1部分中,它只为那些不需要超过1个产品的人添加了1个产品,但我为那些需要超过1个产品添加到购物车的人添加了一个解决方案。

add-to-cart.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;
});

将此代码复制到您的文件中。例如:我的主题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\uuu
替换为所需的值

这段代码使用原来的WooCommerce单一产品页面AddtoCart按钮,但停止其功能,然后使用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;
}

您可以在单个产品中复制存档按钮的行为

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();
        }
你可以在这里看到完整的教程


商业已经开始了。我认为现在解决办法很容易。如果我遗漏了一些内容,那么只需检查“启用AJAX添加到存档上的购物车按钮”并使用
woocommerce\u模板\u循环\u添加到购物车()
函数即可

复选框选项位于Woocommerce>Settings>Products>General下。

然后只需在您希望输出按钮的任何位置使用

如果您像我一样使用自定义循环,您需要确保产品是全局的,以便
woocommerce\u模板\u循环\u添加到\u 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>';

}
add_shortcode('buy_reach','msp_buy_reach__shortcode');
函数msp\u再次购买\u\u快捷码(){
$order\u items=msp\u get\u customer\u unique\u order\u items(get\u current\u user\u id());
回声';
foreach($id形式的订单\项目){
$product=wc\U get\U product($id);
全球$产品;
如果(!空($product)){
?>

要使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);
<script>
$ ('body'). on ('add_to_cart', function () {
     // Callback -> product added
     // $ ('. popup'). show ();
});
</script>
最后在footer.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);
<script>
$ ('body'). on ('add_to_cart', function () {
     // Callback -> product added
     // $ ('. popup'). show ();
});
</script>

$('body')。在('add_to_cart',function(){
//回调->添加了产品
//$('.popup').show();
});

我将此插件用于后端部分

我没有使用产品页面,因此我修改了脚本以使用任何按钮:

(函数($){
$(文档).on('单击','.btn',函数(e){
变量$thisbutton=$(此);
试一试{
var href=$thisbutton.prop('href').split('?')[1];
如果(href.indexOf('add-to-cart')=-1)返回;
}捕捉(错误){
返回;
}
e、 预防默认值();
var product_id=href.split('=')[1];
风险值数据={
产品标识:产品标识
};
$(document.body).trigger('adding_to_cart',[$thisbutton,data]);
$.ajax({
键入:“post”,
url:wc_add_to_cart_params.wc_ajax_url.replace(
“%%端点%%”,
'将\添加到\购物车'
),
数据:数据,
发送前:功能(响应){
$thisbutton.removeClass('added').addClass('loading');
},
完成:功能(响应){
$thisbutton.addClass('added').removeClass('loading');
},
成功:功能(响应){
if(response.error和response.product_url){
window.location=response.product\u url;
复述
<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>
<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>