0

I have custom search template on which I would like that search results include value of one custom field. I tested this code to include custom fields in WP search results, and it works just fine. But, it search through all custom fields. In case there are many diferent custom fields it will slow down search, and of course there is no need that all custom fields are searchable, sometimes it just populate search results with irrelevant results.

I would like to allow searching of just one custom field, on custom search template. Ideally on that template I do not even need to search for post title/content, just for content of that custom field.

How to include just particular custom field in search results?

UPDATE

$search_term = get_search_query(); // Get current search term
$args = array(
     'post_type' => 'post', // Post type is post.
     'post_status' => 'publish', // Post is published.
     'posts_per_page' => 4, // Posts per page.
     'meta_query' => array(
                         array(
                                 'key'     => 'my_custom_field', // Custom field to search
                                 'value'   => $search_term, // Value of custom field is search term
                                 'compare' => 'LIKE',
                            ),
                        ),
            );
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
include 'post-content.php';
endwhile;
}
wp_reset_query();

I managed to get results from one custom field, with code above, but I lost pagination. Now I have no content on /page/x. How to allow pagination in this case?

  • You have "lost" your pagination because you're using a custom query. Post the code for your pagination and we'll see if we can fix it. – TheDeadMedic Nov 28 '16 at 19:26
1

I would ignore the article entirely and use a meta query:

$query = new WP_Query([
    'meta_query' => [
        [
            'key'     => 'my_custom_field',
            'value'   => 'search_term',
            'compare' => 'LIKE',
        ]
    ]
]);
  • I update my question, thanks for sugestion. Could you please look at my update. – Advanced SEO Nov 28 '16 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.