Search using query_args () in wordpress

0

I'm using the following query:

   $args = array(  
'post_type' => 'post', 
'meta_query' => array(
array(
       'key' => 'site_name',
          'value' => $busca,
          'compare' => 'LIKE'
        ),
  ),
);
query_posts($args);

The problem is that it only returns the search for the custom field "site_name". I wanted it to return in general, too. How do I?

    
asked by anonymous 25.02.2017 / 03:06

1 answer

0

This query is rewriting the main query and can not do that. I'll show you another way:

<?php // functions.php

add_filter( 'posts_where', 'busca_meta' );

function busca_meta( $where ) {
    global $wpdb;

    if ( ! is_search() ) {
        return $where;
    } 

    $busca = esc_sql( get_search_query() );

    $where .= "OR ( {$wpdb->postmeta}.meta_key = 'site_name' AND {$wpdb->postmeta}.meta_value LIKE '$busca' )";

    return $where;
}

There's a lot going on here so let's take it easy:

posts_where is the filter where all queries to the database pass, where you can modify the WHERE clause of the SQL that is going to be searched. In your case, since it is a search with the s parameter, the WHERE has already been set to search for the words in the title or body of the post. What we're doing here is to intercept this clause and add another at the end:

$busca = esc_sql( get_search_query() ); is equivalent to its $busca = $_GET['s'] , with the difference that get_search_query() already protects your system against illegal characters that may have come in the query. As this term is going to be thrown straight into SQL I have also added esc_sql() that will finish escaping the term so that you will be safe from SQL injection attacks.

$where .= "OR ...etc"; is where we then add in the query that in addition to searching the title and content, go also to meta_key site_name ;

With this when the system loads your file search.php you will already receive the filtered results, without having to redo the query.

ps: do not use query_posts ()

    
25.02.2017 / 03:37