I have a working query that calls all my posts that have a certain meta value for one of two meta keys:
$term = filter_var( $_GET['term'] );
$query = get_posts( [
'post_type' => 'some_cpt_name',
'meta_query' => [
'relation' => 'OR',
[
'key' => 'foo',
'value' => $term,
'compare' => 'LIKE',
],
[
'key' => 'bar',
'value' => $term,
'compare' => 'LIKE',
],
]
] );
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
$termmaybe is in thepost_title?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
Ok, here’s the final addition using the posts_clauses filter (and edit) as suggested from @scribu:
function alter_posts_where_clause( $where )
{
global $wpdb;
$term = filter_var( trim( $_GET['term'] ), FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE );
if ( is_null( $term ) )
return $where;
$term = $wpdb->esc_like( $term );
// Append to the WHERE clause:
$where .= $wpdb->prepare( " OR {$wpdb->posts}.post_title LIKE '%s'", "%{$term}%" );
return $where;
}
add_filter( 'posts_where', 'alter_posts_where_clause' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0