• Resolved rooseveltrp

    (@rooseveltrp)


    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; ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter rooseveltrp

    (@rooseveltrp)

    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
    
    }
    
    ?>

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

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Fetch Random Posts’ is closed to new replies.