0
votes

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?

1
If you use meta_query you will only get posts where custom field value is apples which will exclude the results that have apples 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

1 Answers

0
votes

Use below code will work for custom field search.

$custom_field = $_GET['custom_field '] != '' ? $_GET['custom_field '] : '';
$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),
    'meta_query'    =>  array(
                          array(
                                'key'     => 'custom_field_key', 
                                'value'   => $custom_field ,
                                'compare' => 'LIKE', 
                                ),
                            )
    );
$results= new WP_Query( $args );

Tested and works well.