WordPress by default displays posts in date order with Ascending or Descending options. What if you prefer to show random posts on your homepage so that every time someone visits your site, they see a different selection of posts.
First off, why would you want to do this. It could be that older posts on your site are just as relevant as newer posts and they don’t get read because they are buried too deep due to their date. While there are a number of plugins that offer this functionality, they usually offer this for widgets only. But what if I told you that you can do this with five lines of code.
Copy the code below and paste into your Child theme’s function file. That’s it.
add_action('pre_get_posts','alter_query');
function alter_query($query){
if ($query->is_main_query() && is_home())
$query->set('orderby', 'rand'); //Set the order to random
}
I have a buddypress with a theme(youzify), I want to display activitys posts randomly on home page, I want posts to be displayed randomly, not in chronological order
anyone knows any code or method for that
To display BuddyPress activity posts in random order on the home page while using the Youzify theme, you can achieve this by modifying the query that fetches BuddyPress activities. Here’s how you can do it:
### Custom Code for Randomizing Activity Posts
1. **Create a Child Theme** (if you haven’t already):
– If you’re directly modifying the theme, changes will be lost after updates. A child theme ensures your custom code persists.
2. **Add Custom Code to `functions.php`**:
Add the following code to your theme’s or child theme’s `functions.php` file:
“`php
function display_buddypress_activities_randomly($args) {
// Check if on the home page
if (is_front_page()) {
// Set the ‘random’ order
$args[‘order_by’] = ‘RAND()’;
}
return $args;
}
add_filter(‘bp_after_has_activities_parse_args’, ‘display_buddypress_activities_randomly’);
“`
This code hooks into BuddyPress’s `bp_after_has_activities_parse_args` filter and modifies the query to order results randomly on the home page.
3. **Clear Cache**:
If your site uses caching (e.g., a caching plugin), clear the cache to ensure the changes are reflected immediately.
4. **Test the Homepage**:
Visit your site’s home page to verify that the activity posts are displayed in random order.
### Additional Notes:
– **Performance Impact**: Using `RAND()` in SQL queries can be resource-intensive on large datasets. If you notice performance issues, consider caching the results or limiting the number of displayed posts.
– **Youzify Compatibility**: The code should work seamlessly with Youzify, as it modifies the BuddyPress query directly. If Youzify has custom query modifications, further debugging might be needed.
– **Styling**: Depending on your theme, you may need to adjust CSS to ensure the randomised activity posts are displayed as intended.