WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Fetch Random Posts (3 posts)

  1. rooseveltrp
    Member
    Posted 6 years ago #

    Hello again,
    My code below basically grabs posts from a specified category and the amount I wish to limit it to.

    But I want to grab a certain amount of random posts from any of my categories as long as they are not private.

    Is there any built in function to do that?

    <?php $recent = new WP_Query("cat=1&showposts=3"); while($recent->have_posts()) : $recent->the_post();?>
    <?php if( get_post_meta($post->ID, "hpbottom", true) ): ?>
    <a href="<?php the_permalink() ?>" rel="bookmark"><img style="float:left;margin:0px 10px 0px 0px;" src="<?php echo get_post_meta($post->ID, "hpbottom", true); ?>" alt="<?php the_title(); ?>" /></a>
    <?php else: ?>
    <a href="<?php the_permalink() ?>" rel="bookmark"><img style="float:left;margin:0px 10px 0px 0px;"  src="<?php bloginfo('template_url'); ?>/images/thumbnail.png" alt="<?php the_title(); ?>" /></a>
    <?php endif; ?>
    <b><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></b>
    <?php the_content_limit(350, "[Read more]"); ?>
    
    <div style="border-bottom:1px dotted #2255AA; margin-bottom:10px; padding:0px 0px 10px 0px; clear:both;"></div>
    
    <?php endwhile; ?>
  2. rooseveltrp
    Member
    Posted 6 years ago #

    After searching with the tag I found my solution. Here's how it works

    <?php
    
    $rand_posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_status = 'publish' AND post_type='post' ORDER BY RAND() LIMIT 4");
    
    foreach($rand_posts as $post)
    {
    	setup_postdata($post);
    ?>
    
    				<?php if( get_post_meta($post->ID, "hpbottom", true) ): ?>
    				    <a href="<?php the_permalink() ?>" rel="bookmark"><img style="float:left;margin:0px 10px 0px 0px;" src="<?php echo get_post_meta($post->ID, "hpbottom", true); ?>" alt="<?php the_title(); ?>" /></a>
    				<?php else: ?>
    				   	<a href="<?php the_permalink() ?>" rel="bookmark"><img style="float:left;margin:0px 10px 0px 0px;"  src="<?php bloginfo('template_url'); ?>/images/thumbnail.png" alt="<?php the_title(); ?>" /></a>
    				<?php endif; ?>
    				<b><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></b>
    				<?php the_content_limit(350, "[Read more]"); ?>
    
    				<div style="border-bottom:1px dotted #2255AA; margin-bottom:10px; padding:0px 0px 10px 0px; clear:both;"></div>
    
    <?php
    
    }
    
    ?>
  3. @mercime
    Volunteer Moderator
    Posted 6 years ago #

    Good for you. You're learning fast, kudos!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags