• I’m currently trying to display 3 posts from a particular category sorted randomly in my sidebar using a query_post, and then display an image from a custom field value. Currently I have two categories, and the following php:

    <?php
    $args=array(
       'cat'=>3,
       'orderby' => 'rand',
       'showposts' => 3
       );
       query_posts($args);
    ?>
    
    <? if (have_posts()) : while (have_posts()) : the_post(); ?>
    <li><?php $featuredimage = get_post_custom_values("featured-image"); if ( $featuredimage != '' ) { ?>
    <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><img src="<?php echo get_option('home'); ?>/wp-content/uploads/<?php echo $featuredimage[0]; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" class="featured-image" /></a>
    <?php } ?></li>
    
    <?php endwhile; else: ?>
    
    <?php _e('Sorry, nothing matched your criteria.'); ?>
    
    <?php endif; ?>

    Sometimes it shows nothing at all, but other times shows the image fine.

    My logic tells me that it’s going through all the categories randomly right?

    Can someone tell me how to make this work and show 3 random posts from category 3… ALL THE TIME regardless of whether on a page, post, archive etc?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter OthelloBloke

    (@othellobloke)

    I managed to work around this by sorting by the custom field using this:

    <?php query_posts('showposts=3&meta_key=featured-image&orderby=rand'); ?>

    But I’d still like to be able to sort by category. Anyone please?

    I did the same thing a couple of days ago and it is working fine for me. This is how I did it:

    <?php query_posts(‘cat=4&showposts=3&orderby=rand’); ?>
    <?php while (have_posts()) : the_post(); ?>
    <? the_title(); ?>
    <? the_content(); ?>
    <?php endwhile; ?>
    <?php wp_reset_query(); ?>

    You need to place the statements in your div containers. The last statement <?php wp_reset_query(); ?> it to reset the query. Without it I ended up having the sidebar posts as the main page’s content as well (the main pages query was over-written).

    Hope that helps. Let me know if you need more info…

    Forgot to mention the custom field. I’d get it using this code before the line <? the_content() ?>. With some css you can have the post nicely wrap around the custom field image.

    <?php global $more;
    $more = 0;
    $custom_field_name = get_post_meta($post->ID,’custom_field_name’, true);
    if ($custom_field_name != “”) { ?>
    <img src=”<? bloginfo(‘url’); ?>/wp-content/uploads/<? echo strtolower($thumbs); ?>” alt=”” class=”indexthumb” />
    <? } ?>

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Show X posts randomly from particular Category’ is closed to new replies.