Saqib Rao
Saqib Rao

Reputation: 379

WP_QUERY Multiple search terms

I am trying to build a better script for my wordpress that will show related posts by splitting the Title of the post and search for posts for each word of the title.

but when I pass the value of 's' arg of WP_QUERY as an array of words. It fails and shows the all post of wordpress

I am stuck. Any solution to pass multiple 's' values. Thanks in advance..

 $search = $_GET['search'];
 $search_terms = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $search, -1, PREG_SPLIT_NO_EMPTY);

            $p_args = array(
                "post_type" => "post",
                "paged" => $paged,
                "s" => $search_terms,
                );

 query_posts($p_args); 

Upvotes: 1

Views: 5424

Answers (2)

ErikPhipps
ErikPhipps

Reputation: 155

WP_Query accepts a string of single keywords joined with a '+' character.

$p_args = array(
    "post_type" => "post",
    "paged" => $paged,
    "s" => "dogs+cats",
);

Upvotes: 4

George L
George L

Reputation: 1

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:

  1. 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;
    
    
  2. 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 sanitised manually.

Even though this worked for me, i'm not sure if it's the best approach.

Upvotes: 0

Related Questions