The posts_pre_query
Hook in WPFTS
The posts_pre_query
hook in WordPress is a filter that allows modification of WP_Query
results before they are returned. WPFTS utilizes this hook in split-query mode (split_the_query
) to retrieve complete post data based on their IDs and relevance scores obtained from the initial query.
What WPFTS Does When posts_pre_query
is Called:
-
Checking Indexed Search and Split Query Mode: The plugin verifies if indexed search is enabled and split query mode is being used (
$wpq->wpftsi_session['use_indexed_search']
and$wpq->wpftsi_session['is_split_query']
). -
Retrieving Complete Post Data: If the conditions are met, WPFTS fetches complete post data from the database using the IDs obtained in the first query. This is done via a separate SQL query to the
wp_posts
table. The plugin also adds arelev
(relevance) field to each post object. Importantly, WPFTS uses a direct SQL query to retrieve data, not the standardget_posts()
function, to avoid caching posts without relevance information. -
Sorting Posts: WPFTS sorts the retrieved posts according to the order defined in the initial query to maintain relevance-based sorting.
Important Functions Involved in posts_pre_query
Handling:
-
WPFTS_Search::index_posts_pre_query()
-
WPFTS_DB::get_results()
(for executing the SQL query) -
wpq_set_found_posts
(indirectly, for settingfound_posts
andmax_num_pages
)
How to Use This in Addon Development:
Addon developers need to understand how WPFTS uses posts_pre_query
in split-query mode. If your addon also modifies this filter, ensure your logic doesn’t conflict with WPFTS. Specifically, consider that in this mode, WPFTS completely replaces the standard post array returned by WP_Query
with its own.
Additional Notes:
-
WPFTS uses
posts_pre_query
only in split-query mode. -
Split query is used to optimize performance with large search result sets.
-
WPFTS sorts posts by relevance while restoring the original order from the first query.