Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active August 4, 2022 17:16
Show Gist options
  • Save luizbills/7948984d880016f52ac334e897228832 to your computer and use it in GitHub Desktop.
Save luizbills/7948984d880016f52ac334e897228832 to your computer and use it in GitHub Desktop.
Adicionar opções do produto aos produtos do loop
<?php
/*
* @version 1.1.0
*/
add_action( 'woocommerce_after_shop_loop_item_title', 'lpb_wc_add_product_options', 9 );
function lpb_wc_add_product_options () {
global $post;
$product = wc_get_product( $post->ID );
if ( ! $product->is_type( 'variable' ) ) return;
$get_variations = sizeof( $product->get_children() ) <= apply_filters( 'woocommerce_ajax_variation_threshold', 30, $product );
$available_variations = $get_variations ? $product->get_available_variations() : false;
if ( $available_variations === false ) return;
$attributes = $product->get_variation_attributes();
$selected_attributes = $product->get_variation_default_attributes();
foreach ( $attributes as $attribute_name => $options ) {
if ( empty( $options ) || ! taxonomy_exists( $attribute_name ) ) continue;
echo '<div class="product-attribute product-attribute-' . esc_attr( $attribute_name ) . '">';
echo '<ul class="attribute-options">';
$terms = wc_get_product_terms( $product->id, $attribute_name, array( 'fields' => 'all' ) );
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $options ) ) {
echo '<li class="attribute-option attribute-option-' . esc_attr( $term->slug ) . '">';
echo '<span class="label">' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) ) . '</span>';
echo '</li>';
}
}
echo '</ul>';
echo '</div>';
}
}
.product-attribute .attribute-options {
list-style: none;
padding: 0;
margin: 0;
}
.product-attribute .attribute-option {
display: inline-block;
margin: 0 0.25em;
padding: 0.2em;
border: 1px solid #ddd;
}
/* não mostrar o nome da opção */
.product-attribute .label {
display: none;
}
/*
Aqui um exemplo de criar "amostras de cores" do produto.
*/
.product-attribute .attribute-option::before {
content: '';
display: block;
box-sizing: border-box;
width: 1em;
height: 1em;
background: #ddd;
}
.product-attribute .attribute-option-black::before {
background: #202020;
}
.product-attribute .attribute-option-blue::before {
background: #5D8DB3;
}
.product-attribute .attribute-option-green::before {
background: #718464;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment