Wordpress - Add post title to meta field query

1.8k views Asked by At

Question: Is there a way to add the built-in s=query into a meta field query OR array?

We want to query on both meta data and post title, for the purpose of a search form. Currently, adding the s=query prevents the meta_query from functioning (which it does so perfectly without).

PHP

// Our search request
$queryString = sanitize_text_field($_REQUEST['query']);

// List of ACF fields to loop through
$customFields = array('title', 'subtitle', 'page_content');

// Setup basic "OR" meta_query for ACF fields
$customFieldsMetaQuery = array(
  'relation' => 'OR'
);

// Insert given ACF fields into meta_query
foreach ($customFields as $field) {
  $customFieldsMetaQuery[] = array(
    'key'      => $field,
    'value'    => $queryString,
    'compare'  => 'LIKE',
  );
}

// Query Arguments
$args = array(
  'post_type'      => array('page'),
  's'              => $queryString, // This line clashes with 'meta_query'
  'meta_query'     => $customFieldsMetaQuery, // This line clashes with 's'
);

// Construct Query
$searchQuery = new WP_Query($args);
1

There are 1 answers

0
radscheit On

You could try something like this, in order to keep the original meta query structure like shown in here.

// Insert given ACF fields into meta_query
foreach ($customFields as $field) {
   $customFieldsMetaQuery[] = array(
'key'      => $field,
'value'    => $queryString,
'compare'  => 'LIKE',
 );
}

// Setup basic "OR" meta_query for ACF fields
$customFields = array(
'relation' => 'OR',
$customFieldsMetaQuery
);