Using get_posts method in WordPress

In previous article we read query_posts() , so get_posts( ) is an alternative of the query_posts(), it retrieves raw post data when called the get_posts() function or method. In administration pages the get_posts() method used to generate or create a list of pages of a particular type, and it may be used within a plugin to catch all raw data for a set of posts and analyze it for patterns such as common terms, external links, or tags with the intent of discarding the content after a quick digestion. There is not intended for user-facing content display because it turns off much of query processing in database and filtering the data that is done within the more general WP_Query approach. Specifically get_posts(), is the ability to set up all of the global data that needed to make the template tags reflect the current post data. Not all template tags are available to the get_posts() by default this the one issue. For fix this deficiency then you need to call the setup_postdata() function to get the template tags for use in your Loop. Below the example is showing how to retrieve or fetch a single random post using the get_posts() method:

<?php$randompost = get_posts( ‘numberposts=1&orderby=rand’ );
foreach( $randompost as $post ) : setup_postdata( $post );?>
<h1><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></h1>
<?php the_content(); ?>
<?php endforeach; ?>

The another major difference using the get_posts() method if you noticed — the value returned is an array. For the array values the foreach loop code is used. This example returns only one post, if you want more than one were returned posts, this would cycle through each. After that the setup_postdata() function is called to fetch the data for your template tags. Also Remember that you can set up your get_posts() parameter for using an array:

<?php
$args  is a variable.
$args = array(‘numberposts’ => 5,’orderby’ => rand) the rand is used for get post randomly;
$randompost = get_posts( $args );

You may see older code although using to get_posts() or query_posts() constructions, The WP_Query is the preferable approach and should be the heart of custom loop syntax. Whatever there are times when you want the get quick-and-dirty access it provided by get_posts() to generate additional data or context for further customization of your Loop or in the plugin.