WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to hook into the loop, ie. have_posts() maybe? and output some code before and after. Is there a filter for this so I can use it in a plugin without needing to edit themes?

share|improve this question
up vote 3 down vote accepted

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() ){

share|improve this answer
This is exactly what I needed. Thank you. – Poe Jul 19 '13 at 20:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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