• Hello

    I was able to have my posts appear randomly by inserting this line on top of my index.php file (found in one of the older topics):

    <?php query_posts($query_string . ‘&orderby=rand’) ?>

    But I’d like to apply this only to posts belonging to a certain category (let’s say “Journal”), so that posts belonging to category “Journal” would appear randomly in my blog while all other posts would appear in chronological order as they normally do.

    If you know the solution, I’d be very grateful for help. I don’t know php at all, so please bear this is mind 🙂

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • for this, do not edit the index.php template, and do not use ‘query_posts()’ – do work with 'pre_get_posts' instead.

    https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

    (untested) example code to be added into functions.php of your (child) theme:

    function random_order_journal_category( $query ) {
        if ( $query->is_category('journal') && $query->is_main_query() ) {
            $query->set( 'orderby', 'rand' );
        }
    }
    add_action( 'pre_get_posts', 'random_order_journal_category' );
    Thread Starter astaroth0803

    (@astaroth0803)

    Thanks for a quick reply.

    This works, but it’s not exactly what I meant. Sorry that I didn’t explain clearly enough.

    What this does is it randomizes posts order only when I enter the “Journal” category (website.com/category/journal/). What I want to do it to have my regular blog page where all posts from all categories are displayed together and have posts from “Journal” category mixed randomly among other posts. Hope that explains it better.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Random post order for a category’ is closed to new replies.