WordPress.org

Support

Support » How-To and Troubleshooting » How to display random posts from a given category?

How to display random posts from a given category?

  • TransPersonal
    Member

    @transpersonal

    Hi guys,

    Right now I’m using the following code to display random posts on my site:

    <?php $randomPost = $wpdb->get_var(“SELECT guid FROM $wpdb->posts WHERE post_type = ‘post’ AND post_status = ‘publish’ ORDER BY rand() LIMIT 1”);
    echo ‘<span>Random Post</span>‘; ?>

    I was wondering how this code can be altered to display random posts from a given category?

    Thanks for your help!

Viewing 5 replies - 1 through 5 (of 5 total)
  • TransPersonal
    Member

    @transpersonal

    My code was stripped. here’s the full code:

    <?php $randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY rand() LIMIT 1");
    echo '<a href="'.$randomPost.'"><span>Random Post</span></a>'; ?>
    TransPersonal
    Member

    @transpersonal

    help please!

    The5sisters
    Member

    @the5sisters

    There is a plug in called ‘Random Posts’ which has a setting option to exclude categories by name.

    TransPersonal
    Member

    @transpersonal

    I’m not trying to exclude categories but to display random posts from a particular category. Anyway, I have too many plugins already and would prefer to do this without any plugins or not do it at all.

    Kai Johnson
    Member

    @kai-johnson

    No plugin needed.

    Add this code to your loop query (tested WP 2.9 working):

    query_posts(array(
    	'showposts' => 6,
    	'orderby' => 'rand',
    	'category_name' => 'News' //You can insert any category name
    ));
    if (have_posts()) : while (have_posts()) : the_post();

    In other words: Query 6 posts, displayed in random order, from the category ‘News’. The key to having your posts display randomly is “orderby”.

    To randomize posts from either of two categories, try:

    query_posts(array(
    	'showposts' => 6,
    	'orderby' => 'rand',
    	'category__in' => array(get_cat_ID('News'),get_cat_ID('Events'))
    ));
    if (have_posts()) : while (have_posts()) : the_post();

    Note: in the example above, I am using get_cat_ID() to grab the id number for a given category. Category__in requires the use of id numbers rather than names.

    To randomize posts that show up in BOTH categories:

    query_posts(array(
    	'showposts' => 6,
    	'orderby' => 'rand',
    	'category__and' => array(5,8))
    ));
    if (have_posts()) : while (have_posts()) : the_post();

    For more info on the variables you can use in query_posts, see the official codex: http://codex.wordpress.org/Template_Tags/query_posts

    Have fun!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to display random posts from a given category?’ is closed to new replies.