I want to modify search results. Currently I hook to the_posts and check wp_query->is_search to determine if I am looking at the search results page.

However, I noticed that the_posts is executed not only on the search results, but also on any excerpt list on the page (such as a listing of news items in the footer of the page.)

How can I tell which the_posts call is which? Should I assume it’s the ‘first’ one? or is there a better way?

1 Answer
1

I’d say it’s perfectly fine to do it the way you’re doing it now, that is

function my_the_posts($posts, $query = false) {
    if( is_search() ){
        // do your thing here
    }
    return $posts;
}
add_filter( 'the_posts', 'my_the_posts' );

Don’t worry about those excerpts in the footer, even though they may be part of the search page (which the footer will be, obviously), they’re part of a different query and so will not pass the is_search() test.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *