Output before and after the loop

The function the_post() (source) triggers the action loop_start when it is first used in the loop. This is used in every WP_Query loop, so you may want to check if the current query is the ‘main’ one (assuming that’s the query you wish to target)

add_action( 'loop_start', 'wpse107113_loop_start' );
function wpse107113_loop_start( $query ){
     if( $query->is_main_query() ){

     }
}

The last time have_posts() is called it triggers the action loop_end (source), so similar to above:

add_action( 'loop_end', 'wpse107113_loop_end' );
function wpse107113_loop_end( $query ){
     if( $query->is_main_query() ){

     }
}

Leave a Comment