如果产品已添加到 WooCommerce 中的购物车,如何重命名“添加到购物车”按钮

时间:2021-04-01 14:29:38

标签: woocommerce

当 Ajax 添加到购物车功能在我的 WooCommerce 商店中处于活动状态时,在 Ajax 添加到购物车上首先单击它会显示一个选中的图标符号,例如:
Add to Cart Button

下面的代码将添加到按钮的购物车文本更改为 "Seçildi !" 如果产品已经在购物车中,则只有在刷新页面后,如:
secildi

//Rename the button on the Product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'ts_product_add_cart_button' );
 
function ts_product_add_cart_button( $label ) {
    
   foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
      $product = $values['data'];
      if( get_the_ID() == $product->get_id() ) {
         $label = __('Seçildi !', 'woocommerce');
      }
   }
    
   return $label;
 
}
 
//Rename the button on the Shop page 
add_filter( 'woocommerce_product_add_to_cart_text', 'ts_shop_add_cart_button', 99, 2 );
 
function ts_shop_add_cart_button( $label, $product ) {
    
   if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() ) 
   {
       
      foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
         $_product = $values['data'];
         if( get_the_ID() == $_product->get_id() ) {
            $label = __('Seçildi !', 'woocommerce');
         }
       }    
   }
    return $label;    
}

但如果您不刷新页面,按钮将保持和以前一样带有选中的图标符号。

我想要的是将添加到购物车按钮更改为已为此产品添加的数量,例如:

3 in cart

这可能吗?我需要改变什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

您可以使用 WC woocommerce_product_add_to_cart_text 动作挂钩,您可以通过所有产品获取 wc 购物车循环并比较路径第二个参数 $prodcuct 对象。检查下面的代码。代码将激活主题functions.php文件。

function change_add_to_cart_text_if_product_already_in_cart( $add_to_cart_text, $product ) {    
    if ( WC()->cart ) {
        $cart = WC()->cart; // Get cart
        if ( ! $cart->is_empty() ) {
            foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                $_product_id = $cart_item['product_id'];
                if ( $product->get_id() == $_product_id ) {
                    $add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
                    break;
                }
            }
        }
    }
    return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );

已更新(根据 OP 要求如何在点击时快速更改文本数量)。

有两种方法可以做到这一点。

  1. 您可以使用 woocommerce_loop_add_to_cart_args 并添加产品数量属性,并在此基础上显示。

     function add_product_qty( $args, $product ){
         if ( WC()->cart ) {
             $cart = WC()->cart; // Get cart
             if ( ! $cart->is_empty() ) {
                 foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                     $_product_id = $cart_item['product_id'];
                     if ( $product->get_id() == $_product_id ) {
                         $args['attributes']['data-product-qty'] = $cart_item['quantity'];
                     }else{
                         $args['attributes']['data-product-qty'] = 0;
                     }
                 }
             }else{
                 $args['attributes']['data-product-qty'] = 0;
             }
         }
         return $args;
     }
     add_filter( 'woocommerce_loop_add_to_cart_args', 'add_product_qty', 10, 2 );
    
     add_action( 'wp_footer', 'ajax_button_text_quick_change_js_script' );
     function ajax_button_text_quick_change_js_script() {
         ?>
         <script>
             (function($) {
    
                 $(document.body).on('click', '.ajax_add_to_cart', function(event){
                     $this = $(this);
                     var product_qty = parseInt($this.attr('data-product-qty')) + 1;
                     $this.attr('data-product-qty',product_qty);
                     var buttonText = '<span class="add_to_cart_text product-is-added">('+product_qty+') Already in cart</span><i class="cart-icon pe-7s-cart"></i>';
                     $this.html(buttonText).attr('data-tip','('+product_qty+') Already in cart');
                 });
    
             })(jQuery);
         </script>
         <?php
     }
    
  2. 您可以使用 added_to_cart jQuery 事件,该事件在添加到您调用 ajax 的购物车后触发并获得 add_to_cart_text 响应。

     add_action( 'wp_footer', 'ajax_button_text_js_script' );
     function ajax_button_text_js_script() {
         ?>
         <script>
             (function($) {
    
                 $(document.body).on('added_to_cart', function(event, fragments, cart_hash, button){
    
                     var product_id  = button.data('product_id'),
                         product_qty = button.data('quantity');
    
                     button.addClass('loading');
    
                     $.ajax({
                         url: "<?php //echo admin_url('admin-ajax.php'); ?>",
                         method: 'POST',
                         data:{action:'change_add_to_cart_text',product_id:product_id},
                         dataType: "json",
                         success: function( response ){
                             var buttonText = '<span class="add_to_cart_text product-is-added">'+response.data.button_text+'</span><i class="cart-icon pe-7s-cart"></i>';
                             button.html(buttonText).attr('data-tip',response.data.button_text);
                             button.removeClass('loading');
                         },error: function (jqXHR, exception) {
                             var msg = '';
                             if (jqXHR.status === 0) {
                                 msg = 'Not connect.\n Verify Network.';
                             } else if (jqXHR.status == 404) {
                                 msg = 'Requested page not found. [404]';
                             } else if (jqXHR.status == 500) {
                                 msg = 'Internal Server Error [500].';
                             } else if (exception === 'parsererror') {
                                 msg = 'Requested JSON parse failed.';
                             } else if (exception === 'timeout') {
                                 msg = 'Time out error.';
                             } else if (exception === 'abort') {
                                 msg = 'Ajax request aborted.';
                             } else {
                                 msg = 'Uncaught Error.\n' + jqXHR.responseText;
                             }
                             console.log(msg);
                         },
                     });
                 });
    
             })(jQuery);
         </script>
         <?php
     }
    
     add_action('wp_ajax_change_add_to_cart_text', 'change_add_to_cart_text');
     add_action('wp_ajax_nopriv_change_add_to_cart_text', 'change_add_to_cart_text');
    
     function change_add_to_cart_text(){
    
         $product_id = $_POST['product_id'];
    
         if ( WC()->cart ) {
             $cart = WC()->cart; // Get cart
             if ( ! $cart->is_empty() ) {
                 foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                     $_product_id = $cart_item['product_id'];
                     if ( $product_id == $_product_id ) {
                         $add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
                         break;
                     }
                 }
             }
         }
    
         wp_send_json_success(array(
             'button_text' => $add_to_cart_text
         ));
     }
    

以下代码仅适用于 OP 站点。

add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_quantity_fields', 99, 2 );
function custom_add_quantity_fields($html, $product) {
    //add quantity field only to simple products
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {

        if ( WC()->cart ) {
            $cart = WC()->cart; // Get cart
            if ( ! $cart->is_empty() ) {
                foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                    $_product_id = $cart_item['product_id'];
                    if ( $product->get_id() == $_product_id ) {
                        $data_product_qty = $cart_item['quantity'];
                    }else{
                        $data_product_qty = 0;
                    }
                }
            }else{
                 $data_product_qty = 0;
            }
         }

        //rewrite form code for add to cart button
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        $html .= woocommerce_quantity_input( array(), $product, false );
        $html .= '<button type="submit" data-quantity="1" data-product_id="' . $product->get_id() . '" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple" data-product-qty="'.$data_product_qty.'">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}   

经过测试并有效。

Shop Page

Product Page