I have a strange question, I have built my site and my loop etc. But on my sidebar I want to add a sort of random post display, but I don't want the entire post to display, I've had some difficulties achieving this so if you have any alternative methods you wish to share, please let me know :)

What I want to achieve at the moment is shorten the content shown, I know you can do this with excerpt() but if you take a look at the method I had to do, you'll see what I mean as I had problems doing it the typical way.

my index:

    wp_reset_postdata();//not sure if this is actually reseting my postdata?

$random=get_posts(array('number posts'=>1,'orderby'=>'rand','category'=>'objects','post-type'/*stops pages being included?*/=>'post','post_status'=>'publish'));
?><h2><a href="<?echo$random[0]->guid;?>">Do you want a <?echo get_the_title($random[0]->ID);?>?</a></h2>
<p><?echo preg_replace("/<img[^>]+\>/i","",get_post_field('post_content',$random[0]->ID));/*custom_excerpt($random[0]->ID);*/?></h2>

I've given it a go in custom_exert but it failed to get the correct post id for some reason? Not surfier I've chosen the correct method for what I want to do. Any suggestions?

  • What do you mean by "correct" ID if they are random? Please note that guid property is not considered a valid permalink, despite that it might work as one.
    – Rarst
    Feb 22, 2015 at 10:29
  • Well using the_content() will return the content of the page rather than the of the post I want (really not sure how it works). I also used esc_url(get_the_permalink($random[0]->ID));
    – bashleigh
    Feb 22, 2015 at 19:36
  • The snippet you included in question doesn't seem to be using the_content() though?
    – Rarst
    Feb 22, 2015 at 19:45
  • I didn't because it returned the page's content I was on, rather than the post content I wanted from my random selection. :d
    – bashleigh
    Feb 22, 2015 at 20:25

1 Answer 1


Give this a try. Basically, your get_posts looks OK, but you need to setup the post information. This leats you use the normal functions the_something and get_something without having to pass in a post object / ID each time. Just remember to call wp_reset_postdata(); anytime you use setup_postdata().

<?php $random_post = get_posts(array(
   'category'     => 'objects',
   'number posts' => 1,
   'orderby'      => 'rand',
   'post-type'    => 'post',
   'post_status'  => 'publish'
)); ?>

<?php if($random_post) : ?>
   <?php setup_postdata($featured_post); ?>

   <?php the_title('<h2>', '</h2>'); ?>
   <?php the_excerpt(); ?>

   <?php wp_reset_postdata(); ?>

<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.