Home › Forums › WoodMart support forum › Swatch appears in product page but not in product grid › Reply To: Swatch appears in product page but not in product grid
November 12, 2018 at 1:18 pm
#88973
Artem Temos
Keymaster
Try to add the following PHP code snippet to the child theme functions.php file to do this
function woodmart_swatches_list( $attribute_name = false ) {
global $product;
$id = $product->get_id();
if( empty( $id ) || ! $product->is_type( 'variable' ) ) return false;
if( ! $attribute_name ) {
$attribute_name = woodmart_grid_swatches_attribute();
}
if( empty( $attribute_name ) ) return false;
$available_variations = $product->get_available_variations();
if( empty( $available_variations ) ) return false;
$swatches_to_show = woodmart_get_option_variations( $attribute_name, $available_variations, false, $id );
if( empty( $swatches_to_show ) ) return false;
$out = '';
$out .= '<div class="swatches-on-grid">';
$swatch_size = woodmart_wc_get_attribute_term( $attribute_name, 'swatch_size' );
if( apply_filters( 'woodmart_swatches_on_grid_right_order', true ) ) {
$terms = wc_get_product_terms( $product->get_id(), $attribute_name, array( 'fields' => 'slugs' ) );
$swatches_to_show_tmp = $swatches_to_show;
$swatches_to_show = array();
foreach ($terms as $id => $slug) {
//Fixed php notice
if ( ! isset( $swatches_to_show_tmp[$slug] ) ) continue;
$swatches_to_show[$slug] = $swatches_to_show_tmp[$slug];
}
}
foreach ($swatches_to_show as $key => $swatch) {
$style = $class = '';
if( ! empty( $swatch['color'] )) {
$style = 'background-color:' . $swatch['color'];
} else if( ! empty( $swatch['image'] ) ) {
$style = 'background-image: url(' . $swatch['image'] . ')';
} else if( ! empty( $swatch['not_dropdown'] ) ) {
$class .= 'swatch-text-only ';
}
$style .= ';';
$data = '';
if( isset( $swatch['image_src'] ) ) {
$class .= 'swatch-has-image';
$data .= 'data-image-src="' . $swatch['image_src'] . '"';
$data .= ' data-image-srcset="' . $swatch['image_srcset'] . '"';
$data .= ' data-image-sizes="' . $swatch['image_sizes'] . '"';
if( woodmart_get_opt( 'swatches_use_variation_images' ) ) {
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $swatch['variation_id'] ), 'woocommerce_thumbnail');
if ( !empty( $thumb ) ) {
$style = 'background-image: url(' . $thumb[0] . ')';
$class .= ' variation-image-used';
}
}
if( ! $swatch['is_in_stock'] ) {
$class .= ' variation-out-of-stock';
}
}
$class .= ' swatch-size-' . $swatch_size;
$term = get_term_by( 'slug', $key, $attribute_name );
$out .= '<div class="swatch-on-grid woodmart-tooltip ' . esc_attr( $class ) . '" style="' . esc_attr( $style ) .'" ' . $data . '>' . $term->name . '</div>';
}
$out .= '</div>';
return $out;
}