Search code examples
phpwordpresswoocommerceproducthook-woocommerce

Show number of variations in WooCommerce shop page


I want to display the number of variations for each product in the Shop Page of WooCommerce, under the Product title, I tried the following:

    add_action( 'woocommerce_after_shop_loop_item', 'custom_echo_stock_variations_loop' );
        
    function custom_echo_stock_variations_loop(){
    global $product;
    if ( $product->get_type() == 'variable' ) {
        
        foreach ( $product->get_available_variations() as $key ) {
            
             echo count($key['attributes']) . ' more variations';
            
        }
        
    }
}

They should return "6 more variations" and "3 More Variations" but I get 111111 and 111 instead.

enter image description here

How can I show array length out of the foreach?


Solution

  • Try this

    add_action( 'woocommerce_after_shop_loop_item', 'custom_echo_stock_variations_loop' );
    
    function custom_echo_stock_variations_loop() {
        global $product;
        if ( $product->get_type() == 'variable' ) {
    
            echo '<br/>'.count( $product->get_available_variations() ) . ' more variations';
        }
    }