• 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….).

Viewing 1 replies (of 1 total)
  • 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

Viewing 1 replies (of 1 total)
  • The topic ‘Generate a Random post but exclude several post’ is closed to new replies.