WP Query Args – Title or Meta Value

How do I query by meta_value or title?

If I set meta_values,

$args['meta_query'] = array(
   'relation' => 'OR',
    array(
        'key' => 'model_name',
        'value' => $thesearch,
        'compare' => 'like'
    )
);

they automatically get added as AND.

This search would be:

 WHERE title = 'Search' AND (model_name = 'Search' OR ...)

I need

WHERE title = 'Search' OR (model_name = 'Search' OR ...)

Solutions Collecting From Web of "WP Query Args – Title or Meta Value"

Note that the relation part in the meta_query argument, is only used to define the relation between the sub meta queries.

You can try this setup:

$args = [ 
    '_meta_or_title' => $thesearch,   // Our new custom argument!
    'meta_query'    => [
        [
            'key'     => 'model_name',
            'value'   => $thesearch,
            'compare' => 'like'
        ]
    ],
];

where we have introduced a custom argument _meta_or_title to activate the meta OR title query.

This is supported by the following plugin:

<?php
/**
 *  Plugin Name:   Meta OR Title query in WP_Query
 *  Description:   Activated through the '_meta_or_title' argument of WP_Query 
 *  Plugin URI:    http://wordpress.stackexchange.com/a/178492/26350
 *  Plugin Author: Birgir Erlendsson (birgire)
 *  Version:       0.0.1
 */

add_action( 'pre_get_posts', function( $q )
{
    if( $title = $q->get( '_meta_or_title' ) )
    {
        add_filter( 'get_meta_sql', function( $sql ) use ( $title )
        {
            global $wpdb;

            // Only run once:
            static $nr = 0; 
            if( 0 != $nr++ ) return $sql;

            // Modify WHERE part:
            $sql['where'] = sprintf(
                " AND ( %s OR %s ) ",
                $wpdb->prepare( "{$wpdb->posts}.post_title = '%s'", $title ),
                mb_substr( $sql['where'], 5, mb_strlen( $sql['where'] ) )
            );
            return $sql;
        });
    }
});