WooCommerce 숍 페이지의 Ajax Add to Cart 버튼에 수량 필드 추가
나는 우코메르스를 처음이야.저는 샵 페이지에 수량 상자를 표시하려고 했습니다.아래 코드를 사용했는데 예상대로 작동합니다.
add_action( 'woocommerce_before_shop_loop', 'handsome_bearded_guy_select_variations' );
function handsome_bearded_guy_select_variations() {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_single_add_to_cart', 30 );
}
그러나 문제는 Ajax Add to Cart 버튼이 기본 버튼으로 대체되었다는 것입니다.
Woocommerce 아카이브 페이지의 수량 필드가 있는 카트 버튼에 Ajax 기능을 다시 활성화하려면 어떻게 해야 합니까?
갱신필 2021년에
WooCommerce 버전 3.2~5+의 경우, JQuery 코드 최적화 및 수량 버그 제거.카트 추가 후 수량 재설정 추가.
다음 커스텀 기능이 접속되어 있습니다.woocommerce_loop_add_to_cart_link필터 후크를 사용하여 WooCommerce 아카이브 페이지 및 기타 제품 루프의 각 제품에 수량 입력 필드를 추가합니다.여기서는 주로 원래 WooCommerce 코드를 사용합니다.
jQuery 코드를 업데이트하려면data-quantity[ Add to Cart ]버튼의 속성을 표시합니다.고객의 희망(및 테마에 따라)에 따라 몇 가지 스타일링이 필요할 수 있습니다.
"카트 보기" 버튼을 숨기기 위한 추가 섹션이 끝에 있습니다.
코드:
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
// Get the necessary classes
$class = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );
// Embedding the quantity field to Ajax add to cart button
$html = sprintf( '%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
woocommerce_quantity_input( array(), $product, false ),
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button' ),
esc_html( $product->add_to_cart_text() )
);
}
return $html;
}
add_action( 'wp_footer' , 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
?>
<script type='text/javascript'>
jQuery(function($){
// Update data-quantity
$(document.body).on('click input', 'input.qty', function() {
$(this).parent().parent().find('a.ajax_add_to_cart').attr('data-quantity', $(this).val());
$(".added_to_cart").remove(); // Optional: Removing other previous "view cart" buttons
}).on('click', '.add_to_cart_button', function(){
var button = $(this);
setTimeout(function(){
button.parent().find('.quantity > input.qty').val(1); // reset quantity to 1
}, 1000); // After 1 second
});
});
</script>
<?php
}
코드는 기능합니다.php 파일(액티브 테마)입니다(액티브 테마).
Storefront 테마로 WooCommerce 버전 4.1.1 및 WordPress 4.5.1에서 테스트 및 작동.
"카트 보기" 버튼 숨기기(Ajax 사용 시 카트에 추가):
1) 이 CSS 규칙을 활성 테마에 있는 styles.css 파일에 추가할 수 있습니다.
a.added_to_cart.wc-forward {
display:none;
}
2) 다음과 같은 후크 기능을 사용할 수 있습니다(첫 번째 옵션이 가장 좋습니다).
add_action( 'wp_head' , 'hide_ajax_view_cart_button' );
function hide_ajax_view_cart_button(){
if( is_shop() || is_product_category() || is_product_tag() ): ?>
<style>
a.added_to_cart.wc-forward {
display:none;
}
</style>
<?php endif;
}
코드가 기능합니다.php 파일(액티브 테마)입니다(액티브 테마).
"수량 버그" 없이 위와 같이 모든 작업을 수행합니다.
코드:
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
// Get the necessary classes
$class = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );
// Adding embeding <form> tag and the quantity field
$html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>%s',
'<form class="cart">',
woocommerce_quantity_input( array(), $product, false ),
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button' ),
esc_html( $product->add_to_cart_text() ),
'</form>'
);
}
return $html;
}
add_action( 'wp_footer' , 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
//if( is_shop() || is_product_category() || is_product_tag() ): ?>
<script type='text/javascript'>
jQuery(function($){
// Update quantity on 'a.button' in 'data-quantity' attribute (for ajax)
$(".add_to_cart_button.product_type_simple").on('click', function() { var $button = $(this); $button.data('quantity', $button.parent().find('input.qty').val()); });
// remove old "view cart" text, only need latest one thanks!
$(document.body).on("adding_to_cart", function() {
$("a.added_to_cart").remove();
});
});
</script>
<?php //endif;
}
참고 자료:
@Loic The Aztec은 2018년 2월 11일 이후 참가.
@braciawrite's와 @andrewmclagan's GitHub은 각각 2015년 12월 11일과 2018년 3월 15일에 출품되었습니다.
https://gist.github.com/webaware/6260326
주의:
수량변경이 아닌 "add_to_cart"버튼을 눌렀을 때 코드가 확인해야 합니다.
저는 이 코드를 WooCommerce 제품과 함께 커스텀 페이지에서 실행하고 있기 때문에 "archives_quantity_fields_script" 함수의 if 및 endif 문을 코멘트 아웃했습니다.
이게 도움이 됐으면 좋겠네요!
이것을 실행하는 데 하루 종일 걸렸지만, 여기 나에게 효과가 있었던 코드가 있습니다.기능을 추가합니다.php - 위에서 수정한 것으로, WooCommerce 5.0.0을 사용하고 있습니다.
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
// Get the necessary classes
$class = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );
// Adding embeding <form> tag and the quantity field
$html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>%s',
'<form class="cart">',
woocommerce_quantity_input( array(), $product, false ),
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button' ),
esc_html( $product->add_to_cart_text() ),
'</form>'
);
}
return $html;
}
add_action( 'wp_footer' , 'archives_quantity_fields_script' );
function archives_quantity_fields_script(){
//if( is_shop() || is_product_category() || is_product_tag() ): ?>
<script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
$( document ).on( 'change', '.quantity .qty', function() {
$( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).attr( 'data-quantity', $( this ).val() );
//alert("Changed");
});
});
jQuery(function($) {
// Update quantity on 'a.button' in 'data-quantity' attribute (for ajax)
$(".add_to_cart_button.product_type_simple").on('click', function() {
var $button = $(this);
$button.data('quantity', $button.parent().find('input.qty').val());
});
// remove old "view cart" text, only need latest one thanks!
$(document.body).on("adding_to_cart", function() {
$("a.added_to_cart").remove();
});
});
</script>
<?php //endif;
}
여기 Woo 3+에서 효과가 있을 것 같은 대체 방법이 있습니다.
<?php
/**
* Add quantity field on the archive page.
*/
function custom_quantity_field_archive() {
$product = wc_get_product( get_the_ID() );
if ( ! $product->is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() ) {
woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
}
}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );
/**
* Enqueue the JavaScript.
*/
function custom_add_to_cart_quantity_handler() {
wc_enqueue_js( '
jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
return false;
});
jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
// For AJAX add-to-cart actions
add_to_cart_button.attr( "data-quantity", jQuery( this ).val() );
// For non-AJAX add-to-cart actions
add_to_cart_button.attr( "href", "?add-to-cart=" + add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
});
' );
}
add_action( 'init', 'custom_add_to_cart_quantity_handler' );
페이지에 표시되는 Ajax 액션에 따라 jQuery에는 몇 가지 옵션이 있을 수 있습니다.
언급URL : https://stackoverflow.com/questions/48722178/add-a-quantity-field-to-ajax-add-to-cart-button-on-woocommerce-shop-page
'programing' 카테고리의 다른 글
| Angular의 필터에서 범위 변수에 액세스합니다.JS (0) | 2023.02.15 |
|---|---|
| 라이브러리 반응 테스트 vs Jaek (0) | 2023.02.15 |
| 브라우저를 프로그래밍 방식으로 새로 고치려면 어떻게 해야 합니까? (0) | 2023.02.15 |
| 스프링 데이터 jpa의 saveAndFlush와 saveAndFlush의 차이 (0) | 2023.02.15 |
| 반응 성분 테스트를 위해 창 크기 변경을 모의하는 방법 파악 (0) | 2023.02.15 |