Support » Plugins » Test if in main loop in add_action('the_post','my_function')

  • ResolvedModerator Jan Dembowski


    Brute Squad and Volunteer Moderator

    This will most likely be poorly worded based on my lack of understanding. Also I’m typing code between two monitors and PCs so this may not be quite correct…

    In my theme’s functions.php file I’m trying to use something like the following to insert HTML above a post in the loop.

    function mh_insert_before_posts( $post ) {
       echo '<!-- insert meaningful references HERE -->';

    Which outputs all over the place where ever we have a loop. I’d like to put in a conditional to confirm I’m in the main loop and THEN perform the echo.

    I can use a counter but adding or subtracting plugins messes up the counter.

    I gave this a read but I’m not getting this portion to work.

    global $wp_query;
    // Check if we're in the main loop
    	if ( $wp_query->post != $post )

    Other tests to see if I’m in the main loop work for other actions.

    For example, from this works:

    function mh_insert_loop_end( $query ) {
       global $wp_the_query;
       if ( $query === $wp_the_query ) {
          echo '<!-- this shows up after the main loop -->';

    And using that test, I’m able to output at the end of the main loop. But I’m having trouble performing the same test for the_post.

    Any pointers would be greatly appreciated. I’m using the current SVN of WordPress 3.3-RC2.


    Jan Dembowski

Viewing 1 replies (of 1 total)
  • Moderator Jan Dembowski


    Brute Squad and Volunteer Moderator

    Self help really is the best. It’s probably not the best way to do it, but I found a test that works as long as your theme has get_header().

    What was happening was that one of my plugins was running the_loop in the head. That screwed up any count/test I had.

    So I needed a test for playing with the posts after the head was completed and I was able to use did_action('wp_enqueue_scripts'). After it’s run it will go from 0 to 1, and if that happens, the head is probably completed.

    add_action( 'the_post' , 'mh_insert_before_posts' );
    function mh_insert_before_posts( $post ) {
       global $mh_post_count;
       $mh_after_head = did_action( 'wp_enqueue_scripts' );
       if ( ( $mh_after_head == 1 ) and ( $mh_post_count < get_option('posts_per_page') ) ) {
          echo '<!-- insert meaningful references HERE -->';

    The counter < get_option('posts_per_page') will ensure that this run’s on the first loop after the head and stop.

    Cool! if someone can share a better test, I would like to hear it though.

Viewing 1 replies (of 1 total)
  • The topic ‘Test if in main loop in add_action('the_post','my_function')’ is closed to new replies.