You added title inside $args['meta_query']
and that’s why your query doesn’t work.
Checking the documentation (get_posts / WP_Query) you will find the available parameters, among them title
and s
.
$args = array(
's' => 'apple',
'post_type' => 'product'
//
// other parameters
// 'status`, 'orderby', 'meta_query', ...
)
$posts = get_posts($args);
If you use the title
parameter – the exact match of the post title will be checked.
bhs_posts.post_title="some text"
If you use s
parameter – (in simplification) the phrase will be splited and searched in the post title, content and excerpt .
((bhs_posts.post_title like '%some%' OR bhs_posts.post_excerpt like '%some%' OR bhs_posts.post_content like '%some%')
AND (bhs_posts.post_title like '%text%' OR bhs_posts.post_excerpt like '%text%' OR bhs_posts.post_content like '%text%'))
If you want to search only in the title of a post, you will need to use posts_search or posts_where filter to modify the query.
add_filter('posts_search', 'se414324_title_search', 100, 2)
function se414324_title_search( $search, $wp_query )
{
global $wpdb;
$qv = &$wp_query->query_vars;
if ( !isset($qv['wpse_title_search']) || 0 == strlen($qv['wpse_title_search']) )
return $search;
$like = $wpdb->esc_like( $qv['wpse_title_search'] ) . '%';
$search = $wpdb->prepare( " AND {$wpdb->posts}.post_title LIKE %s", $like );
return $search;
}
To modify only selected queries, and not all performed by WP, we use our own parameter name, here wpse_title_search
in $args
array.
$args = array(
'wpse_title_search' => 'apple',
'post_type' => 'product',
//
// other parameters
// 'status`, 'orderby', 'meta_query', ...
)
$myquery = new WP_Query($args);
OR
// "suppress_filters" is necessary for the filters to be applied
$args = array(
'wpse_title_search' => 'apple',
'post_type' => 'product',
'suppress_filters' => false,
//
// other parameters
// 'status`, 'orderby', 'meta_query', ...
)
$posts = get_posts($args);