Forums

Generate a Random post but exclude several post (2 posts)

  1. jeffdempsey
    Member
    Posted 4 months ago #

    I am writing a short script that is designed to generate a random post. I also have a session where I keep track of the post they have been to already. I put these pages in a comma delimited variable and attempted exclude them. Here is my sql statement:

    Here is what it looks like in PHP:

    $randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND ID <> ($pageids) ORDER BY rand() LIMIT 1");

    Here is what it looks like when the variables are gone:

    SELECT guid FROM hb_posts WHERE post_type = 'post' AND post_status = 'publish' AND ID <> (1,15,13,20,17,11,5,9,3,0) ORDER BY rand() LIMIT 1

    I can get the code to work fine if I exclude just one post, so the error is in my (1,1,5,20....).

  2. johnkolbert
    Member
    Posted 4 months ago #

    I think you're looking for the "NOT" mysql operator. It negates whatever follows it, so we'll use a "NOT IN", like this:

    $randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND ID NOT IN ($pageids) ORDER BY rand() LIMIT 1");

    Hope that helps

Reply

You must log in to post.

About this Topic