How to ensure “the_content” filter runs only for the main displayed content?

I have a plugin which adds the method to “the_content” filter.

add_filter('the_content', 'myFilteringFunction', 10000);

Read More

Within that function I want to add some links on the beginning and the end of the content. But I only need to do it for the “main” content of the displayed page so – not in the any of the widgets, not in the footer, header etc.

Moreover I only want it to be included for the custom post type which I defined in the same plugin. So I figured out that kind of check, thinking it would be enough.

if( is_single() && get_query_var('post_type') == 'myCustomPostType' && is_main_query() )

Unfortunately it’s not working as intended – at least not in every case.

On the page the plugin WP Types is installed, it’s not working (the links are added despite the condition). Why?

Related posts

2 comments

  1. According to WordPress documentation, you can accomplish this using this code:

    add_filter( 'the_content', 'filter_the_content_in_the_main_loop' );
    
    function filter_the_content_in_the_main_loop( $content ) {
    
        // Check if we're inside the main loop in a single post page.
        if ( is_single() && in_the_loop() && is_main_query() ) {
            return $content . "I'm filtering the content inside the main loop";
        }
    
        return $content;
    }
    

    Or use the same logic via a single line at the beginning of the filter callback function:

    if( !is_single() || !in_the_loop() || !is_main_query() ) return $content;
    
  2. Try adding a condition to your filtering function that checks your post type against get_post_type.

    if ( 'book' == get_post_type() )

    If you wish to apply this filter to pages as well, try is_singular() and include your custom post type(s) as an argument.

    is_singular('book');

    This will return true if any of the following conditions are true:
    is_single()
    is_page()
    is_attachment()
    ‘book’ == get_post_type()

Comments are closed.