skip to Main Content

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?

2

Answers


  1. 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';
        }
    }
    
    Login or Signup to reply.
  2. this code works in the builder (elementor), but the page can no longer be saved (fatal error; 500)

    Code in the function.php of the child theme

    add_shortcode( 'anzahl_varianten', function() {
        global $product;
        $variations = count($product->get_available_variations());
        return '+ '.$variations. ' weitere Varianten';
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search