0

What I want: the array of posts returned by creating $query = new WP_Query($args);

Why: to return specific content as a sort of API request in json format, ready to display on another site


What I tried first:

foreach($query->posts as $post) {
    $post->post_content = apply_filters('the_content', $post->post_content);
};

This performed the autop and do_shortcode filters correctly, but no the oembed transformation.


What I ended up doing:

while($query->have_posts()) : $query->the_post();
    $query->posts[$query->current_post]->post_content = apply_filters('the_content', get_the_content());
endwhile;

The only difference in output, is that inside the loop it performs the oembed, outside it does not. Where does this difference come from, and is there a better way I should have done this?

I checked global $wp_filters and oembed is definitely listed under [8], so it wasn't a filter loading issue.

1 Answer 1

1

There is a difference because you are not using the_post function in the first example. What this function does is it calls setup_postdata function, which sets up all the globals needed for other functions to work. You can call it manually, just at the beginning of your foreach loop, like this: setup_postdata( $post ). In addition it is possible that you would also need to call a global $post; before your foreach loop.

4
  • $wp_filters is already a global variable. How does setting up global post data affect $var = apply_filters('filter_name', $value);?
    – rumpled
    Jan 12, 2013 at 2:25
  • Well, the filter is loaded, but you don't know what exactly happens inside the filter. I have checked the WP_Embed class and it actually uses get_post function in numerous places. Now, if you check get_post function you will learn that it relies on global $post variable, which you haven't specified. The global $post is set during the_post function. Jan 12, 2013 at 3:21
  • BTW, I haven't checked you code in action but just try to call global $post; before your foreach loop (or place the_post(); at the beginning) and see if I am right. Jan 12, 2013 at 3:25
  • Didn't test it fully, but it appears that you are right. I don't understand why a function given a filter name and string as args can't apply the filters in the global wp_filter. Iw guess that's because wordpress is still in transition to oo, so global references still matter. sigh I ended up having to declare global $more inside the loop to display full articles anyway. get_the_content only allows overriding of 'More...' text, but not wether to display it or not.
    – rumpled
    Jan 16, 2013 at 5:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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