I want to shuffle an array and added following filter to my functions.php
add_filter( 'timber/twig', function ( $twig ) { $twig->addFilter( new TimberTwig_Filter( 'shuffle', function ( $array ) { $shuffle = shuffle( $array ); return $shuffle; } ) ); return $twig; } );
However, following code returns nothing:
{% for item in ["WordPress", "React", "Craft", "NodeJS", "Laravel", "Tailwind", "Vue", "Stencil"]|shuffle %} <h2 class="outline">{{ item }}</h2> {% endfor %}
Advertisement
Answer
Following the comment from DarkBee, I got it working with the following code:
add_filter( 'timber/twig', function ( $twig ) { $twig->addFilter( new TimberTwig_Filter( 'shuffle', function ( $array ) { shuffle( $array ); $newArray = []; foreach ( $array as $item ) { array_push( $newArray, $item ); } return $newArray; } ) ); return $twig; } );