Search using query_args() in wordpress

Asked

Viewed 119 times

0

I am 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 tbm. How do I?

  • I don’t understand. You specified in the query that you want posts with meta_key site_name, until then ok. What other you want too?

  • Hello, the problem is that now you are only searching for meta_key. I want to search for the title tbm!

  • is a search of the site?

  • yes, use $search = $_GET["s"];

1 answer

0

This query is rewriting the main query and can’t work like this. 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 through which all queries to the database pass, where you can modify the WHERE clause of the SQL that will be searched. In your case, as is a search with the parameter s o WHERE already set to fetch the words in the title or in the body of the post. What we are doing here is to intercept this clause and add another to 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 will be played straight in SQL added also esc_sql() that will finish escaping the term so that you are 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 the meta_key site_name;

With that when the system loads its file search.php you will already receive the filtered results, without needing to redo the query.

ps: don’t use query_posts()

  • I did not test the code, I wrote it in my head. If I make a mistake, comment here that I fix it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.