[Support request] Display Posts Randomly on Homepage?

Home Forums Support [Support request] Display Posts Randomly on Homepage?

Home Forums Support Display Posts Randomly on Homepage?

Viewing 8 posts - 1 through 8 (of 8 total)
  • Author
    Posts
  • #1422059
    Daniel

    How can I display posts randomly on the homepage? I found a code that works but it only randomizes posts on category pages.

    https://gist.github.com/generatepress/bcee6fc33a22e578885c

    Thanks!

    #1422146
    Leo
    Staff
    Customer Support

    Hi there,

    Good find!

    Try this instead:

    add_action( 'pre_get_posts', 'generate_random_posts', 100 );
    function generate_random_posts( $query ) {
        if ( $query->is_main_query() ) {
            $query->set( 'orderby', 'rand' );
        }
    }
    #1422197
    Daniel

    Thank’s it seems to work but it displays double posts sometimes. Any way to fix that?

    #1422207
    Leo
    Staff
    Customer Support

    Hmm I’m not sure unfortunately.

    Would this work any better?
    https://generatepress.com/forums/topic/randomizing-post-order-on-posts-page/#post-454730

    #1422229
    Daniel

    No same thing happens, any other ideas?

    #1422278
    Leo
    Staff
    Customer Support

    Hmm does the same issue happen if you disable the infinite scroll option?

    #1423857
    Daniel

    Yes the same thing happens.

    #1424138
    Leo
    Staff
    Customer Support

    That’s strange. Any chance you can check with WordPress support to see if they have any ideas?

    If they can provide the code that works in a twenty series default theme, it would work in GP as well as the post loop is completely handled by WordPress 🙂

Viewing 8 posts - 1 through 8 (of 8 total)
  • You must be logged in to reply to this topic.