Using by reference of WP_Query in posts_search filter hook?

Problem:

User is working on a plugin. He was trying to change the WP_Query fired by the requested page.The query itself is based on several _REQUEST parameters he can use to detect and manipulate because they are unique for his plugin.

At first he thought to use the “posts_search” filter hook in his plugin. This hook seemed good as it is passing the WP_Query object by reference. He managed to determine and change the WP_Query object to reflect the new query parameters for his purpose. Unfortunately, this approach didn’t work because the changed WP_Query object was not used for the remainder of the get_posts() method. Instead, it is using $q, which is the shorthand for query_vars: “$q = &$this->query_vars“. Does anyone know how to use the by reference value of the WP_Query object properly for this purpose of manipulating the query settings?
The same applies to other filter hooks in the get_posts() method: “posts_where“, “posts_where_request“, “posts_request” and “posts_results“.

Solution 1:
Have you tried using the pre_get_posts hook?
http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
Do use it with caution as you can end up modify all queries at once, but usually it’s a pretty good way to override things.

Solution 2:
Use the pre_get_posts hook. Then use the ->set() method to set query variables.

It passes in the WP_Query object which has a set method.
function my_callback($query) {
$query->set('foo', 'bar' );
}

Conclusion: 2nd solution is preferable for this problem. So use that one.

Leave a Reply

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