Display posts in a random order for a specific category

To display posts in a random order when viewing an archive of a specific category in WordPress, you can achieve this by creating a custom query using the pre_get_posts action hook. This allows you to modify the default query parameters for category archives.

Here’s how you can show posts in a random order for a specific category:

Open your theme’s functions.php file:
You can access this file via your WordPress dashboard by going to “Appearance” -> “Theme Editor” and selecting your theme’s functions.php file.

Add the following code at the end of your functions.php file:

php code

function custom_category_archive_query($query) {
    if (is_category() && $query->is_main_query()) {
        // Replace 'your-category-slug' with the slug of the specific category
        $category_slug = 'your-category-slug';

        // Check if the current query is for the specific category
        if ($query->query_vars['category_name'] == $category_slug) {
            $query->set('orderby', 'rand'); // Set orderby parameter to 'rand' for random order
        }
    }
}
add_action('pre_get_posts', 'custom_category_archive_query');

Make sure to replace ‘your-category-slug’ with the actual slug of the category for which you want to display posts in random order.

Save the changes to your functions.php file.
Now, when you visit the archive page for the specified category, the posts will be displayed in random order.

Please note that using random order for category archives can make it challenging for users to find specific content, as the order will change each time they visit the page. Make sure this is the desired behavior for your website and content before implementing this solution.

techhipbettruvabetnorabahisbahis forumuedueduedusedueduseduedueduedusedus