WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] I’m trying to display a random post

[Resolved] I’m trying to display a random post

  • So I need to display a random post, but in a seperate loop. So I’m using the following code

    global $wpdb;
    q = "SELECT COUNT(*) FROM $wpdb->post2cat,$wpdb->posts,$wpdb->categories WHERE
    $wpdb->post2cat.post_id = $wpdb->posts.ID and $wpdb->post2cat.category_id = $wpdb->categories.cat_ID and $wpdb->posts.post_status = 'publish' and $wpdb->categories.cat_ID = 5";
    $s = $wpdb->get_var($q);
    $intOffset = rand(1,intval($s));
    echo $s . "<br/>" . $intOffset;
    $my_query = new WP_Query('cat=5&showposts=1&offset=$intOffset');
    if ($my_query->have_posts()) :
    while ($my_query->have_posts()) : $my_query->the_post();

    The value of $intOffset is displaying a random variable between the limits specified, but for some reason it’s not working when I pass it as an offset value cause the latest post is the only displayed.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Nevermind, I’ve figured it out.

    Hi jugularbean, would you be willing to post your fixed code here, i have been struggling trying to get this same function on my site. i’ve tried modifiying random post listing code to make it show content, but with no luck. you seem to have solved it perhaps?
    i’m not a programmer but i’m familiar with wordpress coding enough to get along.

    cheers

    whooami

    @whooami

    Member

    shuffle(query_posts("all your other crap in here"));

    hi whooami, that’s just a bit too brief for my programming skills, could you elaborate on your post please? is shuffle a built-in wordpress code? thanks

    whooami

    @whooami

    Member

    no, shuffle is a built-in PHP function

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘[Resolved] I’m trying to display a random post’ is closed to new replies.
Skip to toolbar