0

I have a custom post type called people.

I want to have 3 search fields for; first-name, middle-name and last-name

I was thinking about creating a page with my own search boxes and use query_posts:

<?php query_posts( array( 'post_status' => 'publish' ,
                             'post_type' => array( 'people' ),
                             'meta_query' => array(
                                 array  (
                                     'key' => 'last-name',
                                     'value' => $last,
                                     'compare' => 'LIKE'
                                 ),
                                 array  (
                                     'key' => 'first-name',
                                     'value' => $first,
                                     'compare' => 'LIKE'
                                 ),
                                 array  (
                                     'key' => 'middle-name',
                                     'value' => $middle,
                                     'compare' => 'LIKE'
                                 )
                             )

                            )
                     ); ?>

Is this the correct way to search?

1

Your basic query logic looks fine assuming you want an AND relationship between the first, middle, and last names but query_posts is never, ever, ever the right way to do anything.

Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.

Create a new WP_Query object and use that instead.

$args = array(
  // your arguments as above
);
$q = new WP_Query($args);
if ($q->have_posts()) {
  while ($q->have_posts()) {
    $q->the_post();
    the_title(); // etc.
  }
}
  • ohh.. ok just as well I asked ;) Would it be bad to replace the default archive (www.example/people/) with a template (archive-people.php) that handles this searching? Its just that an archive in this context is useless, or can it be disabled? – Oliver Jul 1 '15 at 12:26
  • If you don't want the archive, register the post type without one, but you can create a custom archive template as well. Be aware that the main query will still run which could be a wasteful use of resources. – s_ha_dum Jul 16 '15 at 13:47

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.