Site logo

Archived topic

Randomizing post order on posts page

13 replies · Started by NBC on December 20, 2017

Viewing posts 1–14 of 14

I use the posts page to display work samples that I set up as individual posts. The chronological order in which posts appear makes no sense for what's essentially a portfolio page.

I do load randomized posts in a sidebar on my samples pages, but that's not the same thing as randomizing the posts on the posts page itself.

I've looked for a plug-in that would randomize the samples. All of them work only in sidebars.

I've looked for code I can add to my child theme. Nothing I've found works.

Any suggestions?

Yessss! That's perfect!

Thanks so much, Tom!

You're welcome :)

This solution does have one unexpected consequence. It randomizes the Posts listing in the dashboard. That can make it difficult to find the post you want to edit, because when you load page 2, the list randomizes again. Kinda like playing Whac-a-Mole. :-)

I can work around it (log in; visit the site to load the page I want to edit; click on the "Edit" link at the top of the page).

Ah, try this instead:

function tu_rand_posts( $query ) {
    if ( $query->is_main_query() && ! is_admin() ) {
        $query->set( 'orderby', 'rand' );
    }
}
add_action( 'pre_get_posts', 'tu_rand_posts' );

Thank you, Tom! That's exactly it. You're super!

Glad I could help :)

Hi, Tom (and Leo):

I'm posting this question here because it relates directly to the rest of the thread.

The site I was building at the time I started this thread is live now (allfornonprofits.com).

I notice that if I bring up the main sample page (the posts page) through the "Our work" link, and scroll down until the "Continue" button appears, I get repeats of posts that already loaded.

Anything in particular I need to do to forestall that?

This is on the Our Work page? I just gave it a shot and didn't notice any duplicated posts.

Maybe try clearing your browser cache.

Let me know :)

I load another batch of posts using the "Continue" button, and that's when the repeated posts appear.

Hi, Tom:

Looks like that takes care of it! I tested it on my localhost dev server and will implement on the running site.

Thank you again for all you do!

Glad I could help! :)

This archived topic is closed to new replies.