Верх страницы
Обложка к записи Дропдаун с количеством товара в WooCommerce
Время для прочтения: 2 мин. 15 сек.

Дропдаун с количеством товара в WooCommerce

Как-то я переделывал сайт одного из своих клиентов на WooCommerce под названием CELIAS и меня попросили добавить дропдаун с выбором количества товаров.

Цель

Добавить дропдаун с выбором минимального и максимального количества товара.

Минимальный выбор — 10 позиций, максимальный — 500 с шагом 10 (например, 10, 20, 30, …, 500 ).

На странице магазина при добавлении товара в корзину минимальное количество позиций устанавливается в 10.

Код, который я использовал для этого (добавьте его в файл functions.php вашей дочерней темы):

/** 
 * Исходный код взят из https://gist.github.com/kloon/6495019 
 * и доработан при поддрежке Helga в этом gist
 * https://gist.github.com/helgatheviking/ff8792fbb12f5c5367c816b8a46c70ad
 *
 * Change the quantity input to select.
 * @param  array           $args Аргументы инпута.
 * @param  WC_Product|null $product Объект товара.
 * @param  boolean         $echo Вернуть или вывести результат?
 * @return string
 */

function woocommerce_quantity_input( $args = array(), $product = null, $echo = true ) {
	if ( is_null( $product ) ) {
		$product = $GLOBALS['product'];
	}
	$defaults = array(
		'input_id'     => uniqid( 'quantity_' ),
		'input_name'   => 'quantity',
		'input_value'  => '10',
		'classes'      => apply_filters( 'woocommerce_quantity_input_classes', array( 'input-text', 'qty', 'text' ), $product ),
		'max_value'    => apply_filters( 'woocommerce_quantity_input_max', 500, $product ),
		'min_value'    => apply_filters( 'woocommerce_quantity_input_min', 10, $product ),
		'step'         => apply_filters( 'woocommerce_quantity_input_step', 10, $product ),
		'pattern'      => apply_filters( 'woocommerce_quantity_input_pattern', has_filter( 'woocommerce_stock_amount', 'intval' ) ? '[0-9]*' : '' ),
		'inputmode'    => apply_filters( 'woocommerce_quantity_input_inputmode', has_filter( 'woocommerce_stock_amount', 'intval' ) ? 'numeric' : '' ),
		'product_name' => $product ? $product->get_title() : '',
	);
	$args = apply_filters( 'woocommerce_quantity_input_args', wp_parse_args( $args, $defaults ), $product );

	$args['min_value'] = max( $args['min_value'], 10 );
	$args['max_value'] = 10 < $args['max_value'] ? $args['max_value'] : 500;

	if ( '' !== $args['max_value'] && $args['max_value'] < $args['min_value'] ) {
		$args['max_value'] = $args['min_value'];
	}
	ob_start();
	if ( $args['max_value'] && $args['min_value'] === $args['max_value'] ) {
		
		echo '<div class="quantity hidden">
			<input type="hidden" id="'. esc_attr( $args['input_id'] ) .'" class="qty" name="'. esc_attr( $args['input_name'] ) .'" value="'. esc_attr( $min_value ) .'" />
		</div>';
	
	} else {
		/* 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' );
		
		echo '<div class="quantity">'; 
		do_action( 'woocommerce_before_quantity_input_field' );
			
		echo '<label class="screen-reader-text" for="'. esc_attr( $args['input_id'] ) .'">'. esc_attr( $label ) .'</label>';
		
		$options = '';
		for ( $count = $args['min_value']; $count <= $args['max_value']; $count = $count + $args['step'] ) {
			$options .= '<option value="' . $count . '" '. selected( $args['input_value'], $count, false ) . '>' . $count . '</option>';
		}
		echo '<div class="quantity_select"><select name="' . esc_attr( $args['input_name'] ) . '" title="' . _x( 'Qty', 'Product quantity input tooltip', 'woocommerce' ) . '" class="qty">' . $options . '</select></div>';
		do_action( 'woocommerce_after_quantity_input_field' );
		
		echo '</div>';
		
	}
	if ( $echo ) {
		echo ob_get_clean(); // WPCS: XSS ok.
	} else {
		return ob_get_clean();
	}
}

function mihdan_min_quantity( $args, $product ) {
    $args['quantity'] = 10;
    return $args;
}
add_filter( 'woocommerce_loop_add_to_cart_args', 'mihdan_min_quantity', 10, 2 );
add_filter( 'woocommerce_quantity_input_min', 'mihdan_min_quantity', 10, 2 );

Результат

Ссылки

Автор: Кобзарёв Михаил

Русский разработчик с 20-ти летним стажем. Работаю с PHP, ООП, JavaScript, Git, WordPress, Битрикс, Joomla, Drupal, Opencart, DLE, Laravel, Moonshine, SuiteCRM.

Оптимизирую сайты под Google Page Speed, настраиваю импорты для больших магазинов на WooCommerce + WP All Import. Пишу плагины на заказ. Все мои услуги.

Веду блог о разработке, дайджест в телеграмме и в ВК.

Вы всегда можете нанять меня.

Комментарии
Подписаться
Уведомить о
guest

0 комментариев
Межтекстовые Отзывы
Посмотреть все комментарии
Предыдущая запись
Следующая запись

Давайте дружить
в Телеграме

Авторский блог вашего покорного слуги в Telegram про web, программирование, алгоритмы, инструменты разработчика, WordPress, Joomla, Opencart, Laravel, Moonshine, фильмы и сериалы