Forums

Help to display random post from one cat (6 posts)

  1. mserafim
    Member
    Posted 3 years ago #

    I have this code :

    <?php
    	$recent = new WP_Query("cat=5&showposts=1 "); while($recent->have_posts()) : $recent->the_post();?>
    <b><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></b>
    				<?php the_content_limit(130, ""); ?>

    This code displays one latest post from cat "5" and trim the content to 130 characters.

    What i want is to get an random post from cat"5" not the first one.

    Thank you.

  2. Ivovic
    Member
    Posted 3 years ago #

    Check out this page http://codex.wordpress.org/Template_Tags/get_posts

    You can use get_posts fairly easily to retrieve a random post.

  3. mserafim
    Member
    Posted 3 years ago #

    i tried but when i use the random code it shows same port, it doesn't randomize the post. ( even when refresh the page, same post is displayed ).

    Please i need this . Thank you

  4. mserafim
    Member
    Posted 3 years ago #

    no one ? please

  5. Dunkkan
    Member
    Posted 3 years ago #

    <ul>
    <?php
     $rand_posts = get_posts('category_name=WHATEVER&numberposts=5&orderby=rand');
     foreach( $rand_posts as $post ) :
     ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
     <?php endforeach; ?>
    </ul>

    It should work !

  6. thelocallanding
    Member
    Posted 2 years ago #

    I had something very similar to mserafim's code, and all I needed to randomize the list was the &orderby=rand after cat=5&showpsots=1

    works fine! Thanks Dunkkan.

    Using mserafim's example, it would now look like this:

    <?php
    	$recent = new WP_Query("cat=5&showposts=1&orderby=rand"); while($recent->have_posts()) : $recent->the_post();?>
    <b><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></b>
    				<?php the_content_limit(130, ""); ?>

Topic Closed

This topic has been closed to new replies.

About this Topic