get_post_fields as an excerpt

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:

if(have_posts()){
    while(have_posts()):the_post();
        get_template_part('content',get_post_format());
    endwhile;
    wp_reset_postdata();//not sure if this is actually reseting my postdata?
}
get_sidebar();

$random=get_posts(array('number posts'=1,'orderby'='rand','category'='objects','post-type'/*stops pages being included?*/='post','post_status'='publish'));
?h2a 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?

Topic wp-reset-postdata the-content Wordpress

Category Web


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(); ?>
   ...etc...

   <?php wp_reset_postdata(); ?>
}

<?php endif; ?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.