Nested calls the the_content filter

I’m writing a plugin that adds some custom content near the end of a post (or page). So I’ve added a filter for ‘the_content’, and the plugin adds its content there. Mostly, it works.

However, some sites show the entire content of several posts on the homepage (rather than just excerpts). On those sites, my filter is being called once for every post that is displayed. So the custom content shows up more than once.

Read More

Is there some way for me to detect when my filter is a nested call? I.e. that it is being called for the content of a post which is being displayed on the homepage. I could then add my custom content only when it is a “top level” call.

I also considered attaching my filter to the footer instead of the content, but I’ve run across themes that don’t have a footer.

Thanks!
Ken

Related posts

Leave a Reply

1 comment

  1. Single filter call

    Just give this plugin a try. It illustrates the whole technique.

    <?php
    /** Plugin Name: (#69351) Example single filter call on <code>'the_content'</code> */
    function wpse69351_single_call( $content )
    {
        // Only for single view request (post, page, etc.)
        if ( ! is_singular() )
            return $content;
    
        // This removes the filter during its first call
        remove_filter( current_filter(), __FUNCTION__ );
    
        $custom = '<h1>I am only here once!</h1>';
    
        return $content.$custom;
    }
    add_filter( 'the_content', 'wpse69351_single_call' );
    

    If you’re not targeting the content itself, but more the LOOP, then try this example plugin.

    <?php
    /** Plugin Name: (#69351) Example single filter call on <code>'loop_start'</code> &amp; <code>'loop_end'</code> */
    function wpse69351_single_call( $wp_query )
    {
        // Abort in some case
        if ( 'post' !== get_query_var( 'post_type' ) )
            return;
    
        // This removes the filter during its first call
        remove_filter( current_filter(), __FUNCTION__ );
    
        return print '<h1>I am only here once!</h1>';
    }
    // Attach something to the START of the loop
    add_action( 'loop_end', 'wpse69351_single_call' );
    // Attach something to the END of the loop
    add_action( 'loop_start', 'wpse69351_single_call' );
    

    Incomplete Themes

    I also considered attaching my filter to the footer instead of the content, but I’ve run across themes that don’t have a footer.

    Never ever even dare to think about caring for incomplete themes. We got Theme development guidelines for a reason and a call to wp_footer(); is a must have for every theme. Else, just think “it’s crap!” by yourself and move on.