Right now the below function outputs all variations images of a product. E.g. 3x blue (size S, M, L), 3x red (size S, M, L)
I would like the below function to only output unique color images. E.g. 1x blue, 1x red
Tried to use array_unique in the echo string but could not get it working.
Thank you for helping.
function loop_display_variation_attribute_and_thumbnail() {
global $product;
if( $product->is_type('variable') ){
foreach ( $product->get_visible_children() as $variation_id ){
// Get an instance of the Product_Variation object
$variation = wc_get_product( $variation_id );
// Get "color" product attribute term name value
$color = $variation->get_attribute('pa_color');
if( ! empty($color) ){
// Display "color" product attribute term name value
echo $color;
// Display the product thumbnail with a defined size (here 30 x 30 pixels)
echo $variation->get_image( array(30, 30) );
}
}
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This is more of a PHP programming question than specific to WordPress, but you could do something like this.
This keeps a track of which colors have been shown in $shownColors array and doesn’t show the same one twice.
function loop_display_variation_attribute_and_thumbnail() {
global $product;
if( $product->is_type('variable') ){
$shownColors = Array();
foreach ( $product->get_visible_children() as $variation_id ){
// Get an instance of the Product_Variation object
$variation = wc_get_product( $variation_id );
// Get "color" product attribute term name value
$color = $variation->get_attribute('pa_color');
if( ! empty($color) && !in_array($color, $shownColors) ){
// Display "color" product attribute term name value
echo $color;
// Display the product thumbnail with a defined size (here 30 x 30 pixels)
echo $variation->get_image( array(30, 30) );
$shownColors[] = $color; // add this to colors we've shown
}
}
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0