WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Order by rand with no duplicates (8 posts)

  1. gashface
    Member
    Posted 2 years ago #

    I am using multiple loops to grab certain categories ordered by RAND. The problem is when I put things in more than 1 category there can be duplicate results across the loops.

    Is there a way to stop this from happening or not?

  2. TCBarrett
    Member
    Posted 2 years ago #

    Possibly, you could grab the ids in the first query and add them to the post__not_in argument of the second?

    http://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters

  3. gashface
    Member
    Posted 2 years ago #

    [code moderated - please follow the forum guidelines for posting code]

    So how would this work with this code?

  4. alchymyth
    The Sweeper & Moderator
    Posted 2 years ago #

  5. gashface
    Member
    Posted 2 years ago #

    Hi there. I am doing this, but it is still not working, any help?

    http://pastebin.com/4SXKi4WK

    I think maybe because this is assuming you're getting the posts from the same category whereas I need to get them from two seperate ones, but were a post is in both, make sure only it is displayed once from one category?

  6. gashface
    Member
    Posted 2 years ago #

    Ok I've managed to get it working, but occasionally my second loop only gets 2 posts instead of 3, any ideas?

    http://pastebin.com/7zhg0nQi

  7. alchymyth
    The Sweeper & Moderator
    Posted 2 years ago #

    that does happen with the 'continue' method, because the code grabs 3 posts and then 'jumps over' any duplicates;

    there is the other method (also described in here http://codex.wordpress.org/The_Loop#Multiple_Loops_in_Action ) which is using 'post__not_in';

    see:
    http://pastebin.com/fjSZB9aQ

    (btw: make sure to use the category slug (not the category title) with the 'category_name' parameter http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters )

  8. gashface
    Member
    Posted 2 years ago #

    Thankyou that worked perfectly and I've changed to slugs (:

Topic Closed

This topic has been closed to new replies.

About this Topic