WordPress.org

Forums

Question About A Random Post Plugin (6 posts)

  1. crysacraig
    Member
    Posted 7 years ago #

    I was wondering if anyone knows of a way I can get a sinle post, of my choice from a category I chose on my homepage. I want to include an excerpt of the post and a link to the rest of the post... like what is shown on this site http://www.book-blog.com/ above the amazon banner.

    Can someone give me a line of code I can use to do that or is there a plugin?

    Thanks very much

  2. wp_guy
    Member
    Posted 7 years ago #

    I guess you could do a custom database call, like so:

    <?php
    
    $random_post = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY RAND() LIMIT 1");
    
    echo $random_post->post_content;
    echo '<br />';
    echo '<a href="'.$random_post->guid.'">Read More...</a>';
    
    ?>

    That would echo the whole post content, not just the excerpt... I'm not sure how to get the excerpt right now... anyone?

  3. crysacraig
    Member
    Posted 7 years ago #

    Thanks wp_guy for responding.

    o.k. when I add that all that shows up is the read more. Is there some custom/additional code I have to add or change??

    Does anyone else know how to get an excerpt in there as well.

  4. wp_guy
    Member
    Posted 7 years ago #

    Aah! my bad... I hadn't actually tried the code.

    Here's the good one:

    <?php
    
    $random_post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY RAND() LIMIT 1");
    
    setup_postdata($random_post);
    
    the_content("Read More...");
    
    ?>

    That one will work fine and show the excerpt (if you use the <!--more--> tag).

  5. wp_guy
    Member
    Posted 7 years ago #

    Just noticed the 'read more...' link isn't right for some reason...

  6. wp_guy
    Member
    Posted 7 years ago #

    Got it!

    <?php
    
    $rand_posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY RAND() LIMIT 1");
    
    foreach($rand_posts as $post){
    
    	setup_postdata($post);
    
    	the_excerpt("Read More...");
    
    }
    
    ?>

    Works 100% (you can choose to use the_content() instead of the_excerpt() if you'd like).

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags