I have a working query that calls all my posts that have a certain meta value for one of two meta keys:

$term = $_GET['term'];
$args = array(
     'post_type' => 'some_cpt_name'
    ,'meta_query' => array(
         'relation'     => 'OR'
        ,array(
             'key'     => 'foo'
            ,'value'   => $term
            ,'compare' => 'LIKE'
         )
        ,array(
             'key'     => 'bar'
            ,'value'   => $term
            ,'compare' => 'LIKE'
         )
    ) 
);
$query = query_posts( $args );

I need to query all posts that have the $term as meta key "foo" or "bar" or as post title. Problem is how to add the post title as additional possible key?

Q: How can I also check if the $term maybe is in the post_title?

link|improve this question

feedback

2 Answers

up vote -1 down vote accepted

As with most questions involving OR clauses, the answer is the same: use a custom query or alter WP_Query using the 'posts_clauses' filter.

link|improve this answer
Not really the answer as I was searching for the query string, but enough to be marked as answer. Thanks. – kaiser Dec 29 '11 at 20:11
feedback

Ok, here's the final addition using the posts_clauses filter (and edit) as suggested from @scribu:

function alter_example_query( $query )
{
    global $wpdb;

    $term = trim( $_GET['term'] );
    $term = like_escape( $term );

    // Append to the WHERE clause:
    $query['where'] .= $wpdb->prepare( " OR {$wpdb->posts}.post_title LIKE '%s'", "%{$term}%" );

    return $query;
}
add_filter( 'posts_clauses', 'alter_example_query' );
link|improve this answer
SQL INJECTION ALERT! codex.wordpress.org/Class_Reference/… – scribu Dec 29 '11 at 21:17
No need for uppercase letters. This is only the simplified example and I'm performing some stuff to the input term before. Here goes the Qs: A) Why is it necessary for this part of the string? At least it's only part of the query and it runs through the normal functions. B) How would I use $wpdb->prepare with the LIKE '%%s%' statement? I already gave it a try before, but didn't get behind the wpdb error. – kaiser Dec 30 '11 at 2:06
@scribu NVM. Found a function (and moved the leading and trailing % to the $term) to get around the % problem. See update. – kaiser Dec 30 '11 at 2:14
1  
Uppercase was necessary, since I'm sure other users would have came along and used the code as-is. esc_attr() and sanitize_term_filed() are not needed here. – scribu Dec 30 '11 at 8:11
@scribu Ok. As always with my stuff: Feel free to edit. – kaiser Dec 30 '11 at 10:16
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.