- Help Center Home
- Getting started
- Introducing FacetWP
- Installation and updates
- FAQ
- How it works
- What are facets?
- Facet types
- Indexing
- Listing templates
- Extras & integrations
- Add-on features and extras
- Using FacetWP with …
- Built-in integrations
- Advanced Custom Fields
- WooCommerce
- SearchWP
- WP-CLI
- Add-on integrations
- Elementor
- Beaver Builder
- WP Recipe Maker and Tasty Recipes
- Relevanssi
- WPML and Polylang
- Pods
- Meta Box
- Flatsome (theme)
- External integrations
- Listify (theme)
- Listable (theme)
- WPGraphQL
- Document Library Pro
- Tips & tricks
- WooCommerce plugins
- WordPress multi-site
- WP Job Manager
- WP All Import
- Easy Digital Downloads
- EDD Reviews
- Intuitive Custom Post Order
- Custom Taxonomy Order
- Post Types Order
- Genesis framework
- WP External Links
- ElasticPress
- Caching & hosting
- WP Rocket
- Cloudflare
- New Relic
- WP Engine
- Fast Velocity Minify
- Incompatibilities
- Incompatible plugins
- Troubleshooting
- Troubleshooting guide
- Using the right query
- Common issues
- Get support
- Developers
- Hooks reference
- JavaScript reference
- Shortcodes reference
- FacetWP REST API
- How FacetWP works
- Tutorials
- Code snippets
- Changelog
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 (including pagination), 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.