I am filtering the content with the the_content
filter. Everything works perfect, excerpt that my changes are applied to custom queries as well. My changes appear in the sidebar as well if the widget uses a custom query
To counter that, I’m using is_main_query()
to target the main query only, but it is not working. Changes are simply still applied to all queries through out. What is funny though, all other conditional checks like is_single()
and is_category()
is working if I target specific pages, except that all changes affect any other custom query on that page, whether I use is_main_query()
or not
Am I missing something here. How do I apply my changes to the main query only using the the_content
filter
add_filter('the_content', 'custom_content');
function custom_content($content){
if(is_main_query()){ // << THIS IS NOT WORKING
// My custom content that I add to the_content()
}
return $content;
}
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.