WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Test if in main loop in add_action('the_post','my_function') (2 posts)

  1. 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.

    add_action('the_post','mh_insert_before_posts');
    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 http://scribu.net/wordpress/inserting-a-banner-between-posts.html 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 )
    		return;

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

    For example, from http://alexking.org/blog/2011/06/01/wordpress-code-snippet-to-detect-main-loop this works:

    add_action('loop_end','mh_insert_loop_end');
    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.

    Thanks,

    Jan Dembowski

  2. 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') ) ) {
          $mh_post_count++;
          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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.