Automattic\WooCommerce\Blocks\BlockTypes\AddToCartWithOptions

VariationSelectorAttributeOptions::render_dropdownprotectedWC 1.0

Render the attribute options as a dropdown.

Method of the class: VariationSelectorAttributeOptions{}

No Hooks.

Returns

String. The dropdown.

Usage

// protected - for code of main (parent) or child class
$result = $this->render_dropdown( $attributes, $content, $block );
$attributes(array) (required)
Block attributes.
$content(string) (required)
Block content.
$block(WP_Block) (required)
Block instance.

VariationSelectorAttributeOptions::render_dropdown() code WC 10.7.0

protected function render_dropdown( $attributes, $content, $block ) {
	$attribute_id    = $block->context['woocommerce/attributeId'];
	$attribute_slug  = wc_variation_attribute_name( $block->context['woocommerce/attributeName'] );
	$attribute_terms = $block->context['woocommerce/attributeTerms'];
	$default_option  = array(
		'label'      => esc_html__( 'Choose an option', 'woocommerce' ),
		'value'      => '',
		'isSelected' => false,
	);

	$attribute_terms = array_merge(
		array( $default_option ),
		$attribute_terms
	);

	$selected_attribute         = $this->get_default_selected_attribute( $attribute_slug, $attribute_terms );
	$autoselect                 = $attributes['autoselect'] ?? false;
	$disabled_attributes_action = $attributes['disabledAttributesAction'] ?? 'disable';

	$options = '';
	foreach ( $attribute_terms as $attribute_term ) {
		$option_attributes = array(
			'value'                  => $attribute_term['value'],
			'data-wp-bind--selected' => 'state.isOptionSelected',
			'data-wp-bind--disabled' => 'state.isOptionDisabled',
			'data-wp-bind--hidden'   => 'hide' === $disabled_attributes_action ? 'state.isOptionDisabled' : null,
			'data-wp-context'        => array(
				'option' => $attribute_term,
			),
		);

		if ( $attribute_term['value'] === $selected_attribute ) {
			$option_attributes['selected'] = 'selected';
		}

		$options .= sprintf(
			'<option %s>%s</option>',
			$this->get_normalized_attributes(
				$option_attributes
			),
			esc_html( $attribute_term['label'] )
		);
	}

	return sprintf(
		'<select %s>%s</select>',
		$this->get_normalized_attributes(
			array(
				'class'              => 'wc-block-add-to-cart-with-options-variation-selector-attribute-options__dropdown',
				'id'                 => $attribute_id,
				'data-wp-context'    => array(
					'name'          => wc_attribute_label( $block->context['woocommerce/attributeName'] ),
					'options'       => $attribute_terms,
					'selectedValue' => $selected_attribute,
					'autoselect'    => $autoselect,
				),
				'data-wp-init'       => 'callbacks.setDefaultSelectedAttribute',
				'data-wp-on--change' => 'actions.handleDropdownChange',
				'name'               => $attribute_slug,
			),
		),
		$options,
	);
}