the_content and is_main_query

To be honest, the function in_the_loop() is what you are looking for:

add_filter( 'the_content', 'custom_content' );

function custom_content( $content ) {
    if ( in_the_loop() ) {
        // My custom content that I add to the_content()    
    }
    return $content;
}

What in_the_loop does is to check if global for $wp_query (that is the main query object) of the current post is -1 < $current_post < $post_count.

That happens when the main query is looping, because before loop starts, current post is -1, and after loop ends, current post is reset to -1 again.

So, if in_the_loop() is true, it means that the main query object is looping, which is what you need in this case (and is the same result of adding the action on loop_start and removing on loop_end, like the answer @ialocin wrote; in fact it works for the same reason, and got my +1).

Benefit of @ialocin’s approach is when you want to target a different query object than main one, because in_the_loop() only works for main query.

Leave a Comment