Random Ordering in FacetWP
To sort results randomly within a FacetWP Template, you can set orderby
to rand
:
<?php return [ "post_type" => [ "post" ], "post_status" => [ "publish" ], "posts_per_page" => "10", "orderby" => [ "rand" => "ASC", // sort by random "title" => "ASC" // title as a fallback sort ] ];
Since FacetWP is ajax-based, the problem is that the results will be re-randomized on each facet interaction, which is less than desirable.
Fortunately, we can fix this issue with some extra code in functions.php
:
<?php function preserve_random_order( $orderby ) { $seed = floor( time() / 10800 ); // randomize every 3 hours $orderby = str_replace( 'RAND()', "RAND({$seed})", $orderby ); return $orderby; } add_filter( 'posts_orderby', 'preserve_random_order' );
Hat tip to Alex Durston at Amp Web Design for the code example.