Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am doing a rather complicated custom query on a blog's front page, and trying to show the results using The Loop as shown here: Displaying posts using a custom SELECT query

The query filters posts by a custom field that contains a date (show only posts where that field is set to today or later), and orders them by that date.

The query returns the correct posts, but if I turn them over to The Loop, the results are shown as if I were doing a regular query, not the specialized one (i.e. the wrong posts show up).

The people in this forum thread have the same problem; I utilized the $GLOBALS workaround shown there, but to no avail.

  global $post;
  global $wpdb;

 $querystr = "SELECT wposts.* FROM $wpdb->posts wposts ...... some conditions and joins";
 $eventsPosts = $wpdb->get_results($querystr, OBJECT);

 print_r($eventsPosts); // shows CORRECT data      

 if ($wpdb->num_rows > 0)
  foreach ($eventsPosts as $post) 
   {

    /* workaround */
    $stored_post = clone $GLOBALS['post']; // Why, Wordpress, why?
    $GLOBALS['post'] = $post;              // Why are you making me do such terrible things?

    setup_postdata($post);
    the_post();
    the_title(); // shows INCORRECT post

    /* workaround: Restore global */
    $GLOBALS['post'] = clone $stored_post;

   }

however, this output gives me the result as if I had done a regular query, not my special one. Ie, the_title() outputs the title of a post that isn't in the query result.

If I test output the custom query result:

print_r($eventsPosts);

I get the correct posts. Only when I use Loop functions, the wrong results are output.

Is there a canonical, correct way of doing this that works?

share|improve this question
add comment

1 Answer

Turns out I didn't follow the instructions in the manual to the letter: I seem to have declared global $post too early. I don't entirely see through this but it works fine now using this code:

$eventsPosts = $wpdb->get_results($querystr, OBJECT);

if ($eventsPosts)
 {
   global $post;
   foreach ($eventsPosts as $post) 
    { 
     setup_postdata($post);
     the_title(); // or whatever - the loop functions work
    }  
 }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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