我通过以下方式扩展搜索功能:向搜索查询对象添加自定义查询变量pre_get_posts
这样就可以将tax\\u查询和meta\\u查询作为搜索条件。除了查询变量s
是空的,Wordpress重定向到存档页面,这并不理想,因为我仍然希望它基于其他查询变量(tax\\u query&meta\\u query)搜索帖子。我在想也许这和环境有关is_search
布尔值。所以我试着手动将其设置为true
但它被覆盖并恢复为false
. 有没有办法强制它,使其始终为真,从而使Wordpress保持在搜索页面中,即使查询变量为s
是否为空?还是我做得不对?这是我的课程:
class Custom_Query {
private $_get;
private static $_instance;
public function __construct() {
$this->_get = $_GET;
add_filter( \'pre_get_posts\', array( $this, \'pre_get_posts\' ), 9999 );
add_filter( \'wp\', array( $this, \'remove_product_query\' ) );
}
/**
* Hook into pre_get_posts to do the main product query
*
* @access public
* @param mixed $q query object
* @return void
*/
function pre_get_posts( $q ) {
// We only want to affect the main query
if ( !$q->is_main_query() || is_admin() )
return;
$meta_query[] = $this->date_meta_query();
$q->set( \'meta_query\', $meta_query );
$tax_query[] = $this->category_tax_query();
$q->set( \'tax_query\', $tax_query );
$q->set( \'is_search\', true );
}
/**
* Returns date meta query
*
* @return array $meta_query
*/
function date_meta_query() {
$meta_query = array();
$compare = \'=\';
$value = $this->to_date( $this->_get[\'ptp_date\'] );
if ( isset( $this->_get[\'ptp_date_start\'] ) && isset( $this->_get[\'ptp_date_end\'] ) ) {
$compare = \'BETWEEN\';
$value = array( $this->to_date( $this->_get[\'ptp_date_start\'] ), $this->to_date( $this->_get[\'ptp_date_end\'] ) );
}
$meta_query = array(
\'key\' => \'_event_date\',
\'value\' => $value,
\'compare\' => $compare
);
return $meta_query;
}
/**
* Returns category taxonomy query
*
* @return array $tax_query
*/
function category_tax_query() {
$tax_query = array();
$terms = array( (int) $this->_get[\'ptp_term_id\'] );
$operator = \'IN\';
$tax_query = array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'id\',
\'terms\' => $terms,
\'operator\' => $operator
);
return $tax_query;
}
/**
* Converts date string into supported DATE format
*
* @param $date
* @return string $date
*/
function to_date( $date ) {
return date( \'Y-m-d H:i:s\', strtotime( $date ) );
}
/**
* Remove the query
*
* @access public
* @return void
*/
function remove_product_query() {
remove_filter( \'pre_get_posts\', array( $this, \'pre_get_posts\' ) );
}
}