WordPress как на ладони

wc_dropdown_variation_attribute_options()WC 2.4.0

Вывод выбор опций вариативного товара для использования в формах корзины.

Возвращает

null. Ничего (null).

Шаблон использования

<form>
	<?php

	wc_dropdown_variation_attribute_options([
		'options'   => $options,
		'attribute' => $attribute_name,
		'product'   => $product,
		'selected'  => $selected
	]);

	?>
</form>

Использование

wc_dropdown_variation_attribute_options( $args );
$args(массив)

Параметры (аргументы). Возможные ключи массива:

  • options(массив)
    Массив с произвольными опциями.
    По умолчанию: false

  • attribute(массив)
    Название атрибута, по которому нужно генерировать опции.
    По умолчанию: false

  • product(объект)
    Объект продукта Woocommerce.
    По умолчанию: false

  • selected(массив)
    Выбранная опция.
    По умолчанию: false

  • name(строка)
    Название таксономии атрибута.
    По умолчанию: ''

  • id(строка)
    Значение для атрибута id тега select.
    По умолчанию: ''

  • class(строка)
    Значение для атрибута class тега select.
    По умолчанию: ''

  • show_option_none(строка)
    Массив с произвольными опциями.
    По умолчанию: __( 'Choose an option', 'woocommerce' )

По умолчанию: array()

Примеры

2

#1 Урезанный вариант из шаблона выбора опций

Смотреть код файла /templates/single-product/add-to-cart/variable.php

<form class="variations_form cart"
	  action="<?php echo esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); ?>"
	  method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>"
	  data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ); // WPCS: XSS ok. ?>"
>
	<table class="variations" cellspacing="0">
		<tbody>
		<?php foreach ( $attributes as $attribute_name => $options ) : ?>
			<tr>
				<td class="label">
					<label for="<?php echo esc_attr( sanitize_title( $attribute_name ) ); ?>"><?php echo esc_html( wc_attribute_label( $attribute_name ) ); ?></label>
				</td>
				<td class="value">
					<?php
					$selected = isset( $_REQUEST[ 'attribute_' . $attribute_name ] )
						? wc_clean( urldecode( wp_unslash( $_REQUEST[ 'attribute_' . $attribute_name ] ) ) )
						: $product->get_variation_default_attribute( $attribute_name ); // WPCS: input var ok, CSRF ok, sanitization ok.

					wc_dropdown_variation_attribute_options( array(
						'options'   => $options,
						'attribute' => $attribute_name,
						'product'   => $product,
						'selected'  => $selected,
					) );

					echo end( $attribute_keys ) === $attribute_name
						? wp_kses_post( apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#">' . esc_html__( 'Clear', 'woocommerce' ) . '</a>' ) )
						: '';
					?>
				</td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
</form>

Список изменений

С версии 2.4.0 Введена.

Код wc_dropdown_variation_attribute_options() WC 8.7.0

function wc_dropdown_variation_attribute_options( $args = array() ) {
	$args = wp_parse_args(
		apply_filters( 'woocommerce_dropdown_variation_attribute_options_args', $args ),
		array(
			'options'          => false,
			'attribute'        => false,
			'product'          => false,
			'selected'         => false,
			'required'         => false,
			'name'             => '',
			'id'               => '',
			'class'            => '',
			'show_option_none' => __( 'Choose an option', 'woocommerce' ),
		)
	);

	// Get selected value.
	if ( false === $args['selected'] && $args['attribute'] && $args['product'] instanceof WC_Product ) {
		$selected_key = 'attribute_' . sanitize_title( $args['attribute'] );
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
		$args['selected'] = isset( $_REQUEST[ $selected_key ] ) ? wc_clean( wp_unslash( $_REQUEST[ $selected_key ] ) ) : $args['product']->get_variation_default_attribute( $args['attribute'] );
		// phpcs:enable WordPress.Security.NonceVerification.Recommended
	}

	$options               = $args['options'];
	$product               = $args['product'];
	$attribute             = $args['attribute'];
	$name                  = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );
	$id                    = $args['id'] ? $args['id'] : sanitize_title( $attribute );
	$class                 = $args['class'];
	$required              = (bool) $args['required'];
	$show_option_none      = (bool) $args['show_option_none'];
	$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' ); // We'll do our best to hide the placeholder, but we'll need to show something when resetting options.

	if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) {
		$attributes = $product->get_variation_attributes();
		$options    = $attributes[ $attribute ];
	}

	$html  = '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '" data-show_option_none="' . ( $show_option_none ? 'yes' : 'no' ) . '"' . ( $required ? ' required' : '' ) . '>';
	$html .= '<option value="">' . esc_html( $show_option_none_text ) . '</option>';

	if ( ! empty( $options ) ) {
		if ( $product && taxonomy_exists( $attribute ) ) {
			// Get terms if this is a taxonomy - ordered. We need the names too.
			$terms = wc_get_product_terms(
				$product->get_id(),
				$attribute,
				array(
					'fields' => 'all',
				)
			);

			foreach ( $terms as $term ) {
				if ( in_array( $term->slug, $options, true ) ) {
					$html .= '<option value="' . esc_attr( $term->slug ) . '" ' . selected( sanitize_title( $args['selected'] ), $term->slug, false ) . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name, $term, $attribute, $product ) ) . '</option>';
				}
			}
		} else {
			foreach ( $options as $option ) {
				// This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
				$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
				$html    .= '<option value="' . esc_attr( $option ) . '" ' . $selected . '>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $option, null, $attribute, $product ) ) . '</option>';
			}
		}
	}

	$html .= '</select>';

	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	echo apply_filters( 'woocommerce_dropdown_variation_attribute_options_html', $html, $args );
}
Dez64ru 46//vk.com/dez64ru
Редакторы: Kama 9616, campusboy 4748
2 комментария
    Войти