I have a post_results filter that I want to use to manipulate the results returned from a the query. Let's say that it's supposed to put stars around the first post on the first page, second post on the second page, and so on.

When I watch it work in the main content area, everything looks fine, but when it's triggered by the Recent Posts widget on the sidebar, it's behavior is that of the page number that the main content is on, not the first page that sidebar is showing. For example, if the main content is on page 3, then the third post on the page has stars around it, but the third post in Related Posts widget also has stars around it, even though it's the actually showing the first page of results.

My filter is gated with

if (is_home() && is_main_query()) 

. I can't use in_the_loop(), because the filter is fired before the_post() is called, and so The Loop hasn't been entered yet.

Echoing get_query_var('paged') and $wp_query->query_vars['paged'] show the main content's page number, but if I go into WP's default-widgets.php I see that it's actually using a side query

$r = new WP_Query( apply_filters( 'widget_posts_args', array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true ) ) );

and echoing $r->query_vars['paged'] shows the correct page number, even though my post_filter has already fired on it. Echoing when Related Posts prints the link, shows that is_main_query() returns true, in_the_loop() doesn't like it does in the main content block.

I'm really confused on how I'm supposed to distinguish between these two cases.

  • 2
    Your code please. I can't tell what you are doing, and your explanation is confusing. It would help if you'd try to clear that up. – s_ha_dum May 18 '15 at 10:15
  • Can you elaborate what you're doing "to put stars around" - is this HTML code or CSS styles? – TheDeadMedic May 18 '15 at 11:18
  • The question is essentially "How do you get the WP_Query object or SQL statement that triggered the post_results filter?" Unfortunately, I have a sinking suspicion that the answer is "You can't." – jonathankoren May 18 '15 at 19:08

The answer is to specify all the args on the add_filter() call, and then you can have both the array of posts and the query sent to the callback. add_filter( 'posts_results', 'do_stuff', 10, 2 );

Your Answer

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

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