How To Determine If A Filter Is Called In A Sidebar/Widget Context?

On a parallel thread over on the WordPress hacks forum, someone suggested using in_the_loop() and that works some of the time, with some plugins that use either the_content and/or the_excerpt, but not all of the time with all the plugins I’ve been testing against.

Likewise, I’ve now done further testing using is_main_query() and that works some of the time, with some plugins but not with all of them.

But the magic combination of testing against is_main_query() and in_the_loop() seems to do the trick.

So the (pseudo) code now looks something like this …

add_filter ('the_excerpt', array ($this, 'insert_biography_box'));
add_filter ('the_content', array ($this, 'insert_biography_box'));

function insert_biography_box ($content) {
    if (!in_the_loop () || !is_main_query ()) {
        return $content;
    }

    // do code stuff to append/prepend biography content
    $biography = 'some-magic-function-return-value';
    return $content . $biography;
}

.. which now gives me precisely the behaviour I wanted, against as many plugins that use the content or excerpt filters in the sidebar and/or footer widgets.

Leave a Comment