Up-sait.ru

Создание и продвижение сайтов

Up-sait.ru

Создание и продвижение сайтов

Автоматическое обновление корзины Woocommerce и стилизация кнопок количества товара

Автоматическое обновление корзины Woocommerce

Часто бывает что заказчику необходимо кастомизировать кнопку увеличения количества товара, да еще и чтобы при этом корзина обновлялась автоматически.

для этого нужно Перейти в папку / wp-content / plugins / woocommerce / templates / global и скопировать файл quantity-input.php в папку your-theme / woocommerce / global /

после чего его нужно отредактировать, ниже готовый код

<?php
/**
 * Product quantity inputs
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/global/quantity-input.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerceTemplates
 * @version 7.4.0
 *
 * @var bool   $readonly If the input should be set to readonly mode.
 * @var string $type     The input type attribute.
 */

defined( 'ABSPATH' ) || exit;

/* translators: %s: Quantity. */
$label = ! empty( $args['product_name'] ) ? sprintf( esc_html__( '%s quantity', 'woocommerce' ), wp_strip_all_tags( $args['product_name'] ) ) : esc_html__( 'Quantity', 'woocommerce' );

?>
<div class="quantity">
	<?php
	/**
	 * Hook to output something before the quantity input field.
	 *
	 * @since 7.2.0
	 */
	do_action( 'woocommerce_before_quantity_input_field' );
	?>
	<label class="screen-reader-text" for="<?php echo esc_attr( $input_id ); ?>"><?php echo esc_attr( $label ); ?></label>
	<button class="minus qty_button quantity-button.inc" onclick="event.preventDefault();">-</button>  <!-- кнопка минус -->

	<input
		type="<?php echo esc_attr( $type ); ?>"
		<?php echo $readonly ? 'readonly="readonly"' : ''; ?>
		id="<?php echo esc_attr( $input_id ); ?>"
		class="<?php echo esc_attr( join( ' ', (array) $classes ) ); ?>"
		name="<?php echo esc_attr( $input_name ); ?>"
		value="<?php echo esc_attr( $input_value ); ?>"
		title="<?php echo esc_attr_x( 'Qty', 'Product quantity input tooltip', 'woocommerce' ); ?>"
		size="4"
		min="<?php echo esc_attr( $min_value ); ?>"
		max="<?php echo esc_attr( 0 < $max_value ? $max_value : '' ); ?>"
		<?php if ( ! $readonly ) : ?>
			step="<?php echo esc_attr( $step ); ?>"
			placeholder="<?php echo esc_attr( $placeholder ); ?>"
			inputmode="<?php echo esc_attr( $inputmode ); ?>"
			autocomplete="<?php echo esc_attr( isset( $autocomplete ) ? $autocomplete : 'on' ); ?>"
		<?php endif; ?>
		readonly
	/>
	<button class="plus qty_button quantity-button.dec" onclick="event.preventDefault();" >+</button> <!-- кнопка плюс -->
	<?php
	/**
	 * Hook to output something after quantity input field
	 *
	 * @since 3.6.0
	 */
	do_action( 'woocommerce_after_quantity_input_field' );
	?>
<script>
 //Это скрипт заставляющий кнопки работать
  jQuery( function( $ ) {
	  
	          if ( ! String.prototype.getDecimals ) {
            String.prototype.getDecimals = function() {
                var num = this,
                    match = ('' + num).match(/(?:.(d+))?(?:[eE]([+-]?d+))?$/);
                if ( ! match ) {
                    return 0;
                }
                return Math.max( 0, ( match[1] ? match[1].length : 0 ) - ( match[2] ? +match[2] : 0 ) );
            }
        }
	  
  // Quantity "plus" and "minus" buttons
        $( document.body ).on( 'click', '.plus, .minus', function() {
            var $qty        = $( this ).closest( '.quantity' ).find( '.qty'),
                currentVal  = parseFloat( $qty.val() ),
                max         = parseFloat( $qty.attr( 'max' ) ),
                min         = parseFloat( $qty.attr( 'min' ) ),
                step        = $qty.attr( 'step' );
 
            // Format values
            if ( ! currentVal || currentVal === '' || currentVal === 'NaN' ) currentVal = 0;
            if ( max === '' || max === 'NaN' ) max = '';
            if ( min === '' || min === 'NaN' ) min = 0;
            if ( step === 'any' || step === '' || step === undefined || parseFloat( step ) === 'NaN' ) step = 1;
 
            // Change the value
            if ( $( this ).is( '.plus' ) ) {
                if ( max && ( currentVal >= max ) ) {
                    $qty.val( max );
				 
                } else {
                    $qty.val( ( currentVal + parseFloat( step )).toFixed( step.getDecimals() ) );
			 
                }
            } else {
                if ( min && ( currentVal <= min ) ) {
                    $qty.val( min );
				 
                } else if ( currentVal > 0 ) {
                    $qty.val( ( currentVal - parseFloat( step )).toFixed( step.getDecimals() ) );
					
                }
            }
 
            // Trigger change event
            $qty.trigger( 'change' );
			
        });		  
	     });		
		 
		 
  </script>	
</div>
<?php

помимо этого нужно вставить в functions.php вашей темы код для обновления самой корзины после увеличения количества товара

// Обновление корзины при изменении колич.товара
add_action( 'wp_footer', 'cart_update_qty_script' );
function cart_update_qty_script() {
    if (is_cart()) : // Проверяем страница корзины это или нет
    ?>
<style>
	/* Если хотим скрыть кнопку кнопку "Обновить". */
	button[name="update_cart"]{display: none;}</style>
<script>
jQuery( function( $ ) {
 
	$( 'body' ).on( 'change', '.qty', function() { // поле с количеством имеет класс .qty
		 setTimeout(function() { 
                    $( '[name="update_cart"]' ).trigger( 'click' );
                }, 1300 );
	} );
	
		$( 'body' ).on( 'click', '.quantity-button.inc, .quantity-button.dec', function() { // элементы инкремента/декремента 
		 setTimeout(function() { 
                    $( '[name="update_cart"]' ).trigger( 'click' );
                }, 1300 );
	} );
} );           
</script>
    <?php
    endif;
}
// End Обновление корзины при изменении колич.товара

ну и конечно добавить CSS код для стилизации кастомных кнопок

 <style>
 
.form-group--number {
    max-width: 150px;
}
label.screen-reader-text {
    display: none;
}
 
.form-group--number button {
    border: none;
    position: relative;
    top: 6px;
    right: 6px;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
    width: 20px;
    height: 20px;
    max-width: 20px;
    color: #222;
    font-size: 30px;
    background: none;
}
 .input-text.qty.text {
    top: -10px;
    position: relative;
    border: 0;
    margin: 0;
    padding: 0;
}
.form-group--number button.down {
    left: 12px;
}
.form-group--number button.down:before {
    position: absolute;
    top: 50%;
    left: 50%;
    display: inline-block;
    content: '';
    width: 14px;
    height: 1px;
    background-color: #999;
    -webkit-transform: translate(-50%, -50%) rotate(0deg);
    -moz-transform: translate(-50%, -50%) rotate(0deg);
    -ms-transform: translate(-50%, -50%) rotate(0deg);
    -o-transform: translate(-50%, -50%) rotate(0deg);
    transform: translate(-50%, -50%) rotate(0deg);
}
.form-group--number button.up {
    right: 12px;
}
.form-group--number button.up:before, .form-group--number button.up:after {
    position: absolute;
    top: 50%;
    left: 50%;
    display: inline-block;
    content: '';
    width: 14px;
    height: 1px;
    background-color: #999;
}
 
.form-group--number button.up:before {
    -webkit-transform: translate(-50%, -50%) rotate(90deg);
    -moz-transform: translate(-50%, -50%) rotate(90deg);
    -ms-transform: translate(-50%, -50%) rotate(90deg);
    -o-transform: translate(-50%, -50%) rotate(90deg);
    transform: translate(-50%, -50%) rotate(90deg);
}
.form-group--number button.up:after {
    -webkit-transform: translate(-50%, -50%) rotate(0deg);
    -moz-transform: translate(-50%, -50%) rotate(0deg);
    -ms-transform: translate(-50%, -50%) rotate(0deg);
    -o-transform: translate(-50%, -50%) rotate(0deg);
    transform: translate(-50%, -50%) rotate(0deg);
}
 
.form-group--number .form-control {
    border: 2px solid #eaeaea;
    height: 45px;
    padding: 0 25px;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
    color: #222;
    background-color: transparent;
}
.form-group--number input {
    border-radius: 0;
}
 
</style>
Один ответ
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Вас также может заинтересовать:
Один ответ
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *