the_posts filter been called multiple time

I have create an endpoint so I can do some checkout processing of my cart. Everything is working fine in sense that every thing is hooked up properly. Though I am having issue that to serve the content of my endpoint, I define the_posts filter, where if my “endpoint” is choosen than I check other query_vars and do the processing. It works for me for couple of project.

However in this project, I need to mark my cart as paid and remove it from session. So, as usual under my the_posts filter/action function I define a switch and do the processing. But, when said page is called, cart was not getting marked. I debug and found that the_posts action function was called thrice on my page. and the first call did get it marked and clear session, but next call didn’t find session value and hence it unmark the cart again.

Read More

the three call I have on my page are

  1. From wordpress URL rewrite module [I am guessing this] that it try to pick content or redirect them? [seems like a main_query as well]

  2. I have a custom post type as news that I show in my side header for this I create a new WP_query object, but it still call the_post as it is in header.

  3. My page content call where I actually needed it.

  4. I have another call that is in footer recent post thing. but it doesn’t matter for my purpose.

in my the_post method I check for Query_var

global $wp_query, $wpdb, $cardcomm;
if(isset($wp_query->query_vars[cardcomendpoint]) ) { ... }

since all four call set this query var as true I am not sure how can I ensure that it is called for my purpose only. Any idea how to tackle this?

Related posts

Leave a Reply

1 comment

  1. 'the_posts' is an action fired everytime WP_Query get posts, for main query and for other secondary queries, so when you do something like:

    $foo = new WP_Query($args);
    

    in a widget or elsewhere (shortcode, related posts…) 'the_posts' is triggered again.

    However there is only one main query, so you can use a conditional and do what you do only if the query that trigger the action is the main.

    Luckily 'the_posts' pass to hooked functions the query object so you can check if is the main using WP_Query::is_main_query() method:

    add_action('the_posts', 'check_my_endpoint', 10, 2);
    
    function check_my_endpoint( $posts, $wp_query ) {
    
      if ( $wp_query->is_main_query() ) {
    
        global $wpdb, $cardcomm; // no need to globalize $wp_query, we have a reference to it
    
        if( isset( $wp_query->query_vars[cardcomendpoint]) ) { ... }
    
      }
    
    }