强制搜索始终为真(_S)

时间:2013-04-12 作者:jilseego

我通过以下方式扩展搜索功能:向搜索查询对象添加自定义查询变量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\' ) );
}
}

2 个回复
SO网友:Nicü

您可以强制WordPress加载搜索。当您需要php模板时,请使用以下代码:

add_filter( \'template_include\', \'get_search_template\' );
而不是

$q->set( \'is_search\', true );

SO网友:Mohamed

What i did:

add_action( \'parse_query\', \'search_even_empty\' );
function search_even_empty($query)
{
    if( isset($_GET[\'s\']) ):
        $query->is_search = true;
    endif;
}
结束

相关推荐

Search result by range?

我必须搜索标签或自定义字段中有数字(价格)的帖子:示例152。每个帖子都有价格标签。我如何搜索所有高于价格的帖子,例如,我需要搜索所有标价至少为100的帖子。类似/?s=关键字(&M);价格>=300Thx公司