Looking in other plugins/widgets code , I usually see TWO different methods for a query :

one would be :

$args = array( 'numberposts' => $limit , // or, 1, or 20 ...
                'exclude' => '1049',
                'meta_key' => 'some_meta',
$recent_posts = get_posts( $args ); //or get_recent_posts() or any other function
//end query
foreach( $recent_posts as $recent ){ // do something with array
$pop_string .= '<li><a href="' . get_permalink($recent["ID"]) .'>' . $recent["post_title"] .'</a></li> ';
echo $pop_string;

the second method would be :

$orig_post = $post;
global $post;
// query posts
$my_query = new WP_Query('posts_per_page=5&meta_key=somekey&meta_compare=>=&meta_value=somevalue&orderby=meta_value&order=ASC');
if( $my_query->have_posts() ) {
while( $my_query->have_posts() ) {
$pop_string .= '<li><a href="' . the_permalink() . '" rel="upcomming" title="' . the_title() . '">';
$pospstring .=  the_title() . '</a></li>';

echo $pop_string;
$post = $orig_post;

I am very curious as to What is the difference between them .

(I do not mean the fact that one uses array and one is using direct wp functions. - but more the technical capabilities) I understand that the second one is a "custom loop" and the first one is "outside" a loop - but both can be used in widgets for example, to achieve very similar results (if not equal ..)

  1. Is there something that one can do , that the other can´t ?
  2. Which one is the preferred choice , and when ?
  3. what would be the considerations to use one over the other , and how to choose them?
  4. Is there a performance difference ?
  5. If I want for example to write some simple widgets to get data - which should I choose ? and why ?

query_posts() is just a wrapper for WP_Query that sets the $wp_query global.

|improve this answer|||||
  • so that means they are actually equal ? no difference as to what to use when or what is "best practice" ? – user13279 Feb 12 '12 at 14:36
  • If you look on line 90 of wp-includes/query.php, you can see that query_posts() is just a 3 line function that executes a WP_Query. The difference is that it will automatically setup have_posts() and the_post() (as well as all associated functions), whereas WP_Query will need a specific object, ie: $my_query->have_posts(), in the declaration of the loop. – mor7ifer Feb 12 '12 at 14:42
  • ok .. Thanks for the Uber-quick answer ! – user13279 Feb 12 '12 at 14:43

Your Answer

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