Run posts_where and posts_join only on the main query

Using the pre_get_posts hook, I'm able to take $query as an argument. But on posts_where and posts_join hook, I receive the respective clauses and not the query. The problem is that the hook is running on every query, not just the main one.

Given the following code, the code will be executed once on each query the page runs:

add_filter('posts_join', 'my_join');
function my_join($join) { echo 'lala'; return $join; }

How can I tell if the query is the main one so it only runs once?

Topic posts-where wpdb filters Wordpress

Category Web


Of course! I just had to set the $accepted_args parameter of add_filter() to 2. Like so:

add_filter('posts_join', 'my_join', 10, 2);
function my_join($join, &$query) { echo $query->is_main_query() ? 'y' : 'n'; return $join; }

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.