How Do I Display Variation Swatches on Archive or Shop Page for WooCommerce?

attributes-in-catalog

I added this code via the code widget:

<?php

global $product;
if ( $product->is_type( 'variable' ) ) {
    $default_attributes = $product->get_default_attributes();
 
  
    woocommerce_variable_add_to_cart( $product, $default_attributes, array(), true );
} else {
    woocommerce_simple_add_to_cart();
}
?>

But it does not work with InfiniScroll

3 Likes

Hey did you figure this one out? @Denis

Would like to know this also. I specifically want a dropdown menu on product archive pages when a product has product variations. So then user can choose a product variation and directly add it to the card.

I played around with ChatGPT and got a snippet that works, but i am not good with this. Although it does work (Ajax add to cart enabled in Bricks > Woocommerce), but has errors in. I only hope maybe someone can improve upon this. It seems possible.

The very experimental code snippet for use on a product archive page. When doing custom product archive query loop, dont forget to have dynamic {do_action:woocommerce_after_shop_loop_item} in your “card”.

/**
 * Show a dropdown menu on product archive pages for variable products with variations.
 * When a user selects a product variable from the dropdown menu the product should be added to the cart.
 */
add_action( 'woocommerce_after_shop_loop_item', 'add_variation_select_to_archive_page' );
function add_variation_select_to_archive_page() {
    global $product;
    
    // Check if the product is a variable product
    if ( $product->is_type( 'variable' ) ) {
        // Get the available variations for the product
        $variations = $product->get_available_variations();

        // Only show the dropdown if there are variations available
        if ( ! empty( $variations ) ) {
            ?>
            <form class="variations_form cart" method="post" enctype='multipart/form-data'>
                <?php
                // Add the variation select dropdown to the form
                woocommerce_variable_add_to_cart();
                ?>
            </form>
            <?php
        }
    }
}

When anyone has tips let us know. I know there are certain plugins that do it, but then i can’t built my own product archive loop and be restricted. Also hoping not to have 30 woo plugins.

1 Like

You might want to try using WooCommerce Express Shop Page plugin for what you’re trying to do. Saves you from all the coding plus this plugin also adds quantity input fields aside from variation dropdowns not only to your Shop but category pages as well. This plugin is also easy to setup and control and you’re backed with our 30-day Money Back Guarantee.