Answer the question
In order to leave comments, you need to log in
How to display woocommerce product attributes in product list?
Good morning. Tell me how to display product attributes in this form:
I added a variable product. In the product itself, I added an attribute with the name Quantity and with the values:
And in each value I added my own price: and I added the following code to the functions.php
file :
add_action( 'woocommerce_after_shop_loop_item_title', 'show_attributes', 20 );
function show_attributes() {
global $product;
$product->list_attributes();
}
Answer the question
In order to leave comments, you need to log in
Try like this.
add_action( 'woocommerce_after_shop_loop_item_title', 'show_attributes', 20 );
function show_attributes() {
global $product;
if ($product->product_type == 'variable') {
$attributes = $product->get_attributes();?>
<ul>
<?php $variations_ids = $product->get_children();
foreach ($variations_ids as $variation_id) {
$variation = $product->get_child($variation_id);
$variation_data = $variation->get_variation_attributes();
$attributes = $variation->parent->get_attributes();
$description = array();
$attr_name = '';
if ( is_array( $variation_data ) ) {
foreach ( $attributes as $attribute ) {
if ( ! $attribute[ 'is_variation' ] ) {
continue;
}
$variation_selected_value = isset( $variation_data[ 'attribute_' . sanitize_title( $attribute[ 'name' ] ) ] ) ? $variation_data[ 'attribute_' . sanitize_title( $attribute[ 'name' ] ) ] : '';
$description_name = esc_html( wc_attribute_label( $attribute[ 'name' ] ) );
$description_value = __( 'Any', 'woocommerce' );
if ( $attribute[ 'is_taxonomy' ] ) {
$post_terms = wp_get_post_terms( $variation->id, $attribute[ 'name' ] );
foreach ( $post_terms as $term ) {
if ( $variation_selected_value === $term->slug ) {
$description_value = esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) );
}
}
} else {
$options = wc_get_text_attributes( $attribute[ 'value' ] );
foreach ( $options as $option ) {
if ( sanitize_title( $variation_selected_value ) === $variation_selected_value ) {
if ( $variation_selected_value !== sanitize_title( $option ) ) {
continue;
}
} else {
if ( $variation_selected_value !== $option ) {
continue;
}
}
$description_value = esc_html( apply_filters( 'woocommerce_variation_option_name', $option ) );
}
}
$description[] = rawurldecode( $description_value );
}
$attr_name .= implode( '', $description );
} ?>
<li><?php echo $attr_name;?> - <?php echo $variation->get_price_html();?></li>
<?php } ?>
</ul>
<?php }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question