Read Add a WordPress Search Form in 5 minutes – No code keywords for more information.
WP_Query
WP_Query deals with the posts in an intricate manner as defined in the wp-includes/class-wp-query.php. If you have a whole number of multiple queries, then you can perform multiple loops.
WordPress also provides to its users the facility to carry on more filters to change the WP_Query with the use of those filters. Also, you must know that the WP_Query accepts only the string of single keywords joined with the help of the + character.
You can also try to write a query where you will be needed to do a full-text search against multiple keywords. At any time, you will get a set of words and it will be good for you if you can query on multiple bits of the metadata.
Moreover, with the WP_Query search for multiple keywords, you will put multiple fields in the query parts. This can be done by adding the extra remaining nesting levels in the URL string.
Firstly, I think you should use WP_Query instead of query_posts. On their documentation for query_posts it mentions:
Note: This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query.
Assuming you’d switch to WP_Query, the search parameter or ‘s’ value doesn’t seem to accept an array. According to the documentation, you can only use a string.
Adding an array to this will cause WP_Query to ignore the array.
An approach I followed on a project recently was:
- See the actual SQL query made by WP_Query You can do this by
// Your sample query $query = new WP_Query( array( 'cat' => 4 ) ); // Print the SQL query echo $query->request;
- Create a custom SQL query based on the one above Have a look at the examples shown in the documentation for “Displaying Posts Using a Custom Select Query”.
It should look like
global $wpdb; global $post; $querystr = " SELECT DISTINCT wposts.* FROM $wpdb->posts wposts LEFT JOIN $wpdb->postmeta wpostmeta ON wposts.ID = wpostmeta.post_id LEFT JOIN $wpdb->term_relationships ON (wposts.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE wpostmeta.meta_key = 'customDateField' AND wpostmeta.meta_value >= CURDATE() AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN(1,2) ORDER BY wpostmeta.meta_value ASC LIMIT 4 "; $wpdb->get_results($querystr, OBJECT);
You should note that data passed to a custom query, need to be sanitized manually.
The WP_Query Generator is a helpful tool for the developers. By using this tool, custom code for the WordPress query with WP_Query class can be created very easily.
Click here to know more: