0

I have found a lot of documentation on solving this issue with multiple loops, I'm finding it hard to see a solution for one custom loop.

Problem: I'm using infinite scroll to load in the next page of posts to the homepage. The posts need to be shown in a random order so I need to store which posts have been shown and then exclude them the second time the query is hit.

<?php $my_query = new WP_Query(array('post__not_in'=> $do_not_duplicate, 
                        'orderby' => 'rand',
                        'category_name' => 'projects', 
                        'posts_per_page' => 20, 
                        'paged' => $paged));
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID; ?>

<?php get_template_part( 'entry' ); ?>
<?php endwhile; ?>

I have built this from http://codex.wordpress.org/The_Loop#Multiple_Loops_in_Action - however the approach there is to use $do_not_duplicate in the second loop.

Perhaps I need to shuffle this around a bit, store the posts shown in another way, a cookie? Any guidance appreciated.

2
  • 2
    I don't (completely) get what you're doing right now. Why are you setting $do_not_duplicate to the current post's ID - for each post? Don't you want to keep track of all the posts already handled? I'd rather store the post IDs in an array (and then eventually implode it to get a comma separated string), or create that string by hand (meaning concatenating).
    – tfrommen
    Aug 3, 2013 at 14:41
  • 1
    Infinite scroll is gong to make a new request to the server for the next set of posts. That is the nature of AJAX. That means that your $do_not_duplicate variable will never be populated when it needs to be. You need to find a way to pass that information to the infinite scroll script. I don't see the WordPress specific part of this though. You have that part right, though using paged makes no sense in this context.
    – s_ha_dum
    Aug 3, 2013 at 15:07

1 Answer 1

1

I use this solution in my functions.php

 /*------ order ------*/
session_start();

add_filter('posts_orderby', 'edit_posts_orderby');

function edit_posts_orderby($orderby_statement) {

    $seed = $_SESSION["sem"];

        if (empty($seed)) {
          $seed = rand();
          $_SESSION["sem"] = $seed;
        }

        $orderby_statement = 'RAND('.$seed.')';
        return $orderby_statement;  

}

And additionaly, in the page where you show the posts, in the top of the file, i reset the session variable to can start ordering again random in each reload at this way:

$semilla = rand();

$_SESSION["sem"] = $semilla;

Works for me very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.