Created
September 10, 2015 18:10
-
-
Save RadGH/381f31054434026915fd to your computer and use it in GitHub Desktop.
WooCommerce: Display dropdowns for values of attributes (variations or text)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
global $product; | |
if ( !isset($product) ) return; | |
if ( !method_exists( $product, 'get_attributes' ) ) return; // Doesn't support attributes, won't have a dropdown | |
$attributes = $product->get_attributes(); | |
// Note: <form> is just so this section is styled like the default variation dropdown The form isn't meant to do anything. | |
?> | |
<form class="cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo $product->id; ?>"> | |
<table class="variations" cellspacing="0"> | |
<tbody> | |
<?php | |
foreach( $attributes as $attribute ) { | |
if ( empty( $attribute['is_visible'] ) || ( $attribute['is_taxonomy'] && ! taxonomy_exists( $attribute['name'] ) ) ) { | |
continue; | |
} | |
$title = wc_attribute_label( $attribute['name'] ); | |
$name = $attribute['name']; | |
if ( $attribute['is_taxonomy'] ) { | |
$values = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ); | |
} else { | |
$values = array_map( 'trim', explode( WC_DELIMITER, $attribute['value'] ) ); | |
} | |
natsort($values); | |
?> | |
<tr> | |
<td class="label"> | |
<label for="<?php echo sanitize_title( $name ); ?>"><?php echo $title; ?></label> | |
</td> | |
<td class="value"> | |
<select id="<?php echo esc_attr( sanitize_title( $name ) ); ?>" name="attribute_<?php echo sanitize_title( $name ); ?>" data-attribute_name="attribute_<?php echo sanitize_title( $name ); ?>"> | |
<option value=""><?php echo __( 'Choose an option', 'woocommerce' ) ?>…</option> | |
<?php | |
foreach ( $values as $value ){ | |
if ( isset( $_REQUEST[ 'attribute_' . sanitize_title( $name ) ] ) ) { | |
$selected_value = $_REQUEST[ 'attribute_' . sanitize_title( $name ) ]; | |
} else { | |
$selected_value = ''; | |
} | |
printf( | |
'<option value="%s" %s>%s</option>', | |
esc_attr( $value ), | |
selected( $selected_value, $value, false ), | |
apply_filters( 'woocommerce_variation_option_name', $value ) | |
); | |
} | |
?> | |
</select> | |
</td> | |
</tr> | |
<?php | |
} | |
?> | |
</tbody> | |
</table> | |
</form> | |
<?php |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment