这不是怎么回事pre_get_posts
作品
pre\\u get\\u posts操作允许开发人员通过引用访问$query对象(any changes you make to $query are made directly to the
original object - no return value is necessary).
https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
你所做的完全是错误的。您不会通过“返回”另一个查询
pre_get_posts
, 您可以更改现有查询。我不知道什么是如此复杂,您无法通过一组适当的过滤器来完成,但如果您必须有一些自定义SQL,那么:
function project_modify_default_search( $query ) {
if( $query->is_search && $query->is_main_query() && ! isset( $_REQUEST[\'search\'] ) ) {
//I\'m in my search.php - confirmed
//Reset default $query - not to execute at all
//Do my custom complex query and pass the query as a $wp_query object
//so that I can use the default search.php template
global $wpdb;
$searchQ = sanitize_text_field( get_query_var( \'s\' ) );
// Sample "complex" query
$complex_query = "SELECT SQL_CALC_FOUND_ROWS {$wpdb->posts}.ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_title LIKE \'$searchQ%\' LIMIT 10";
// Use `get_col` to return a simple array of IDs
$custom_search_query = $wpdb->get_col( $complex_query );
// Pass those IDs to the main query
$query->set(\'post__in\',$custom_search_query);
// can\'t kill the default search here or it can break some functions.
// $query->set(\'s\',NULL);
// So we do this:
add_action( \'posts_search\', \'__return_empty_string\' );
} //endif
}
add_action( \'pre_get_posts\', \'project_modify_default_search\' );
同样,可以肯定的是,这是生成复杂查询的错误方法,尤其是考虑到相对于通过一组过滤器修改主查询,您至少有一个额外的查询--
posts_where
,
posts_join
, 等