使用查询创建高级搜索的问题

问题描述:

我在使用自定义查询和使用 $wpdb->get_results($query , OBJECT);

I have a problem in creating advanced search with custom query and using $wpdb->get_results($query , OBJECT);

在 wordpress 中的普通搜索中,当我们搜索 xxx yyyy 或搜索 yyyy xxx 时,我们得到相同的结果,这很好.但是,当我被迫使用查询来创建高级搜索时,搜索字段中的单词序列很重要,并且进一步 xxx yyyy 或搜索 yyyy xxx 不是相同的结果.我想用一个例子说:我创建了两个输入字段,一个用于标题,另一个用于我的帖子的作者(作者只是一个例子,在这个地方是一个自定义字段)我尝试阅读这些字段并在 wordpress 中搜索它们

In Normal search in wordpress when we search xxx yyyy or search yyyy xxx we have same results and it's good. But when I am forced to use query to create an advanced search then sequence of words in search fields are important and further xxx yyyy or search yyyy xxx aren't same result. I want to say with an example: I create two input field one for Title and another for Author of my posts(Author is an example only and in this place is a custom fields ) I try to read these fields and search them in wordpress

<?php
$t = $_REQUEST['title'];
$a = $_REQUEST['author'];
global $wpdb;
$query = "SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id";

if ($t != '') {
    $t_sql = " AND wp_posts.post_title like '%$t%' ";
}

if ($a != '') {
    $a_sql = " AND wp_postmeta.meta_key = 'Author' AND wp_postmeta.meta_value like '%$a%' ";
}
$query .= $t_sql;
$query .= $a_sql;
$pageposts = $wpdb->get_results($query , OBJECT);
global $post;

if ($pageposts):
foreach ($pageposts as $post):
setup_postdata($post);
//...
endforeach;
endif;
?>

按照你的想法,我必须做什么?

In Your idea, What do I must to do?

您可以用 Space 字符拆分搜索词,然后构建查询以查找单词的所有可能顺序.以下是 Title 字段的示例:

You can split up your search terms by a Space character and then construct your query to look up every possible order of the words. Here is an example for your Title field:

// Assuming the title is "One Two Three"
$t = $_REQUEST['title'];

// Split the TITLE by space character
$terms = explode(' ', $t); // $terms = ["One", "Two", "Three"]

// Concats each search term with a LIKE operator
$temp = array();
foreach ($terms as $term) {
    $temp[] = "title LIKE '%".$term."%'";
    // $temp = ["title LIKE %One%", "title LIKE %Two%", ...
}

// Adds an AND operator for each $temp to the query statement
$query = "SELECT * FROM titleTable WHERE (".implode(' AND ', $temp).")";
// $query = SELECT * FROM titleTable WHERE 
       // (title LIKE '%One%' AND title LIKE '%Two%' AND title LIKE '%Three%')