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 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?– Ricardo Moraleida
Hello, the problem is that now you are only searching for meta_key. I want to search for the title tbm!
– Thiago
is a search of the site?
– Ricardo Moraleida
yes, use $search = $_GET["s"];
– Thiago