簡體   English   中英

獲取 WooCommerce Ajax 上的產品 ID、名稱和數量添加到購物車以顯示通知

[英]Get product id, name and quantity on WooCommerce Ajax added to cart to display a notice

瀏覽了大量類似的問題,但到目前為止沒有成功。

我想在常規頁面上顯示一個 WC 通知,命名添加到購物車的最后一項。

通知已啟動並正在運行,但是,到目前為止,我無法識別添加到購物車的最后一項的 ID

我試過這個

    $items = WC()->cart->get_cart();
    $ids = array();
    foreach($items as $item => $values) {
        $_product = $values['data']->post;
        $ids[] = $_product->ID;
    }
    $last_product_id = end($ids);
    $added_product = wc_get_product( $last_product_id );
    $added_product_name = $added_product->get_title();

但據我所知,在 AJAX 調用期間購物車內容不會更新。 獲取產品 ID 最簡單的方法應該是包含它的 AJAX 參數,但無法通過 $_GET 讀取。

有誰知道一種方法來檢索通過 WC hook/jQuery 添加的最后一個項目的產品 ID?

對於 Ajax added_to_cart委托事件。

使用 jQuery 您可以輕松獲取產品 ID產品名稱和已添加到購物車 Ajax 的產品數量。

在此使用 Sweet Alert 組件(SWAL 2)的代碼示例中,當將產品添加到購物車時,我們會顯示一個帶有產品名稱(及其 ID)的消息燈箱:

// Add the product name as data argument to Ajax add to cart buttons
add_filter( "woocommerce_loop_add_to_cart_args", "filter_wc_loop_add_to_cart_args", 20, 2 );
function filter_wc_loop_add_to_cart_args( $args, $product ) {
    if ( $product->supports( 'ajax_add_to_cart' ) && $product->is_purchasable() && $product->is_in_stock() ) {
        $args['attributes']['data-product_name'] = $product->get_name();
    }
    return $args;
}

// On Ajax added to cart, shows a lightbox with the product name (and the product id)
add_action( 'wp_footer', 'ajax_added_to_cart_popup_script' );
function ajax_added_to_cart_popup_script() {
    ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <script type="text/javascript">
    jQuery( function($){
        // On "added_to_cart" live event
        $(document.body).on('added_to_cart', function( a, b, c, d ) {
            var prod_id   = d.data('product_id'), // Get the product name
                prod_qty  = d.data('quantity'), // Get the quantity
                prod_name = d.data('product_name'); // Get the product name

            Swal.fire({
                title: '<?php _e("Added to cart!"); ?>',
                text: prod_name+' ('+prod_id+')',
                showCancelButton: true,
                confirmButtonColor: '#000',
                cancelButtonColor: '#3085d6',
                confirmButtonText: '<?php _e("View-cart"); ?>',
                cancelButtonText:  '<?php _e("Continue shopping"); ?>'
            }).then((result) => {
                if (result.value) {
                    window.location.href = '<?php echo wc_get_cart_url(); ?>';
                }
            });
        });
    });
    </script>
    <?php
}

代碼位於活動子主題(或活動主題)的 function.php 文件中。 測試和工作。

在此處輸入圖像描述

有關的:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM