WordPress.org

Ready to get started?Download WordPress

Forums

How to display random posts from a given category? (6 posts)

  1. TransPersonal
    Member
    Posted 4 years ago #

    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!

  2. TransPersonal
    Member
    Posted 4 years ago #

    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>'; ?>
  3. TransPersonal
    Member
    Posted 4 years ago #

    help please!

  4. The5sisters
    Member
    Posted 4 years ago #

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

  5. TransPersonal
    Member
    Posted 4 years ago #

    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.

  6. Kai Johnson
    Member
    Posted 4 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic