How to programmatically retrieve posts matching a search query in WordPress?

In my plugin code, I would like to execute WP_Query (or similar), which returns all posts matching the given query string, as if the user entered the same string in the WordPress search form. Maybe I'm just tight, but I can't find a way to do this. I would expect to have a special parameter for WP_Query , for example matching , but I don't see any evidence.

I will go through the WordPress code base to see how this is done internally, and I will post the answer here if I find it. I just thought that someone might accidentally find out.

+8
php wordpress
source share
5 answers

Passing the query variable from "s" to WP_Query using the search query will filter the search results for the search query:

 $query_args = array( 's' => 'disquiet' ); $query = new WP_Query( $query_args ); 

The corresponding SQL WHERE generated by this query is as follows:

 AND (((wp_posts.post_title LIKE '%disquiet%') OR (wp_posts.post_content LIKE '%disquiet%'))) 

The default search includes wildcards as shown above, which is most likely what you are looking for. If you need an exact search, you can also pass the query var "exact" => true .

See the get_posts WP_Query method in wp-includes / query.php for more details .

+19
source share

I use this in my plugin:

 $query = new WP_Query(array( 'post_type' => 'any', 'suppress_filters' => TRUE, 'posts_per_page' => '-1' )); foreach ($query->posts as $post) { // ... } 

post_type required if you intend to work with custom post types. suppress_filters prevent the formatting of the content if you need to parse it. posts_per_page will return all posts, not the default value for each page.

+1
source share

Something like that?

 // Check the query variable is available if(!$wp_query) global $wp_query; // If not, global it so it can be read from // Your custom args $args = array( 'the_title' => $search_term ); // Merge the custom args with any for the query already $args = array_merge( $args , $wp_query->query ); // Now do the query query_posts( $args ); 

Or you can try the following:

 $query = array ( 'the_title' => $search_term ); $queryObject = new WP_Query($query); // The Loop... 
0
source share

I believe you are looking for this compare

 $args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'color', 'value' => 'blue', 'compare' => 'LIKE' ) ) ); 

from the Wordpress documentation

 compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. Default value is '='. 
0
source share

This is a simpler and easier way to do a search:

 $query = " SELECT * FROM $wpdb->posts WHERE $wpdb->posts.post_title LIKE '$param2%' AND $wpdb->posts.post_type = 'wp_exposants' ORDER BY $wpdb->posts.post_title "; $wpdb->get_results($query); 
-one
source share

All Articles