I have a custom post type of post_type_1
in WordPress, I also have a custom field in that post type of custom_field_data
I am doing a search for apples
by querying posts using wp_query
like this...
$search_term = 'apples';
$args = array(
'post_type' => array('post_type_1'),
'post_status' => array('publish'),
'posts_per_page' => -1,
's' => sanitize_text_field( $search_term)
);
$results= new WP_Query( $args );
This works correctly and returns all posts with apples
in the title, but I would also like to extend the search to the custom field custom_field_data
so the query will return all posts with apples
in either title or custom field.
What is my best approach? I have tried using a meta_query but haven't been successful. Does anybody have an example?
meta_query
you will only get posts where custom field value isapples
which will exclude the results that haveapples
in title but don't have the matching custom field value. You can achieve this by running two queries one for search and another for custom field and push results in array and print only unique results. Not the best solution but gets you working right away. – Faham Shaikh