Basically, you can use the ‘posts_request’ filter to insert any sort of SQL query you want. The problem is the query will go to the DB connected to the global $wpdb
connection object. What you can do is to connect to the other DB using a new instance of class wpdb. Before the query is run, save the default $wpdb
object into a temporary variable, then copy your new wpdb object to the global $wpdb
. Now WP is connected to the other DB, which is great for your custom query, but will be problematic if WP tries to do anything else. So very soon after the query is run, you need to swap back in the original wpdb object.
The soonest you can swap back the original wpdb object is the ‘posts_results’ filter. You don’t need to filter anything, just return whatever is passed. It’s mainly an opportunity to swap back the original wpdb object.
The other issue is to cause your ‘posts_request’ filter to only alter the query for search queries and nothing else. The second parameter passed to this filter is the current WP_Query object. Check that $query->is_main_query() && $query->is_search()
before doing the DB connection swap and altering the query.
A similar issue occurs when you try to swap back the original wpdb object. The same deal occurs, the current WP_Query object is passed here too, so do the same check as was done previously.
Unless the other DB has the expected resources between the two filter calls, I fear something may go wrong in the interim. If this issue occurs, you’re probably better off submitting a search query to a completely separate code page instead of letting WP handle most of it until those filters are applied. A WP page based on a custom template would work well for this. You could also send requests through /wp-admin/admin-post.php.