我想用外部查询(来自Solr)替换现有的搜索功能,但在search.php
页这是我的密码functions.php
:
add_action(\'pre_get_posts\', \'my_search_query\');
function my_search_query($query) {
if($query->is_search() && $query->is_main_query() && get_query_var(\'s\', false)) {
$desired_query = get_query_var(\'s\', false);
$url = \'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&q=\' . $desired_query . \'~2&wt=json\';
$result = file_get_contents($url);
$data = json_decode($result, true);
$ids = array();
foreach ($data[\'response\'][\'docs\'] as $item)
{
array_push($ids, $item[\'id\']);
}
$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
$query = new WP_Query(array(
\'post__in\' => $ids,
\'post_type\' => array(\'last-news\',\'blog\'),
\'paged\' => $paged,
\'posts_per_page\' => 5,
));
}
return $query;
}
这是
search.php
:
<section class="content">
<div class="page-title pad group">
<h1>
<?php if ( have_posts() ): ?><i class="fa fa-search"></i><?php endif; ?>
<?php if ( !have_posts() ): ?><i class="fa fa-exclamation-circle"></i><?php endif; ?>
<?php echo $wp_query->found_posts ?>
<?php _e(\'Search Results\',\'theme\'); ?>
</h1>
</div>
<div class="pad group">
<div class="notebox">
<?php _e(\'Found\',\'theme\'); ?> "<span><?php echo get_search_query(); ?></span>".
<?php if ( !have_posts() ): ?>
<?php _e(\'Try with another term:\',\'theme\'); ?>
<?php endif; ?>
<div class="search-again">
<?php get_search_form(); ?>
</div>
</div>
<?php
if ( have_posts() ) : ?>
<div class="post-list group">
<?php $i = 1; while ( have_posts() ): the_post();
echo \'<div class="post-row">\';
get_template_part(\'content\'); echo \'</div>\'; endwhile; ?>
</div><!--/.post-list-->
<?php get_template_part(\'inc/pagination\'); ?>
<?php endif; ?>
</div><!--/.pad-->
</section><!--/.content-->
回声
$wp_query->found_posts
返回数字“100”,因此它似乎得到了一些东西,但
have_posts()
函数返回假值。
我做错了什么?我只想在$ids
数组每当搜索完成时,我不需要其他过滤器。
Edit (alternative solution):
我也可以这样做:
add_action(\'pre_get_posts\', \'my_search_query\');
function my_search_query($query) {
if($query->is_search() && $query->is_main_query() && get_query_var(\'s\', false)) {
$desired_query = get_query_var(\'s\', false);
$url = \'http://{SOLR_SERVER}:8983/solr/{CORE}/select?indent=on&q=\' . $desired_query . \'~2&wt=json\';
$result = file_get_contents($url);
$data = json_decode($result, true);
$ids = array();
foreach ($data[\'response\'][\'docs\'] as $item)
{
array_push($ids, $item[\'id\']);
}
$query->set(\'post__in\', $ids );
}
return $query;
}
这一个的问题是,正如我所理解的,搜索将与搜索词一起运行,并且只会返回与特定帖子ID中的词匹配的帖子。我不想做这个操作,因为我已经用solr做过了。此外,Solr允许我进行模糊查询,但在该设置中这不起作用,因为wordpress搜索将返回0个结果,而找不到确切的术语。