Problems in creating advanced search using query

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

In a regular Wordpress search, when searching for xxx yyyy or searching for yyyy xxx we have the same results, which is good. But when I have to use a query to create an advanced search, then the sequence of words in the search fields is important, and then xxx yyyy or the search yyyy xxx are not the same result. I want to say with an example: I create two input fields for Title and another for Author of my messages (the author is an example only in this place - these are 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 should I do?

+4
source share
3 answers

You can divide the search terms into the Space character, and then build your query to see all possible word orders. The following is an example of 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%') 
+3
source

Creating a custom query that looking up in a WP database is not a good way. Use WP_Query for this.

Here is the link in which someone was experiencing the same problem:

https://wordpress.stackexchange.com/questions/18703/wp-query-with-post-title-like-something

+1
source

Actually, I look at your code on web development portals, especially for SQL queries. And I also did not know why when searching xxx, yyyy and yyyy xxx do not match your PHP script. But the only tips I can give you:

 $query .= $t_sql; $query .= $a_sql; // is to add an sql order by keyword like this $query .= " ORDER BY wp_posts . post_title "; 

Give it a try! And do not forget addslashes() when you used the variable $_GET , $_POST or $_COOKIE if your server PHP does not run addslashes() for these variables. You can verify this using the get_magic_quotes_gpc() function.

+1
source

All Articles