Search result by range?

时间:2012-11-07 作者:user23397

我必须搜索标签或自定义字段中有数字(价格)的帖子:示例152。每个帖子都有价格标签。我如何搜索所有高于价格的帖子,例如,我需要搜索所有标价至少为100的帖子。

类似/?s=关键字(&M);价格>=300

Thx公司

2 个回复
SO网友:Stephen Harris

If the price is stored as a custom field you\'ll need to use the meta_query argument of WP_Query (see Codex). For instance:

 //Get posts with custom field \'price\' between 20 and 100
 $price_filtered = WP_Query(array(
     \'meta_query\'=>array(
         array(
            \'key\' => \'price\',
            \'value\' => array( 20, 100 ),
            \'type\' => \'numeric\',
            \'compare\' => \'BETWEEN\'
         ),
      )
 ));

(where price is the key of the custom field). Depending on how you might be implementing this (is it intended to be the \'main query\' or not - you might want to use this at pre_get_posts)

Edit

If filtering a search result:

add_action(\'pre_get_posts\', \'wpse71814_filter_search\');
function wpse71814_filter_search( $query ){
     if( $query->is_search() && isset($_GET[\'min\']) ){

         //Collect user input from $_GET for example
         $user_input_min_value = $_GET[\'min\'];

         $meta_query = $query->get(\'meta_query\');

         $meta_query[] = array(
            \'key\' => \'price\',
            \'value\' => $user_input_min_value,
            \'type\' => \'NUMERIC\',
            \'compare\' => \'>=\'
         );

         $query->set(\'meta_query\',$meta_query);
      }
}

Note: The original answer had a meta query which specified a range. The second answer has a meta query which filters for prices above some minimum value.

Usage: /?s=keyword&min=300

SO网友:Daniel

如果您将价格保存在元字段中,则可以使用meta_query:

<?php
    $the_posts = new WP_Query( array(
        \'meta_key\' => \'price\',
        \'orderby\' => \'meta_value_num\',
        \'order\' => \'ASC\',
        \'meta_query\' => array(
            array(
                \'key\' => \'price\',
                \'value\' => \'100\',
                \'type\' => \'NUMERIC\',
                \'compare\' => \'>=\'
            )
        )
    ));
?>
<?php while ( $the_posts->have_posts() ) : $the_posts->the_post(); ?>
    <h1><?php the_title(); ?></h1>
<?php endwhile; wp_reset_query(); ?>

结束

相关推荐

Rewriting search permalink

在我的搜索字段(/?s=a)中键入“a”时,我的search.php 将加载模板,并显示与该字母匹配的所有结果。如果我将此添加到我的。H访问…RewriteCond %{REQUEST_URI} ^/$ RewriteCond %{QUERY_STRING} ^s=(.+)$ RewriteRule .* /searchmyblog/%1/? [R,L] 然后在我的搜索中键入“a”,将显示我搜索的第一个结果。所以没有search.php 显示所有结果的模板,但页面被重定向到“my