0

I want to query first and last name using custom post type metaboxes.

Code i am using:

$name = 'John Doe';

$args = array( 
    'post_type'     => 'customers',
    'post_status'   => array( 'publish', 'pending', 'draft' ),
    'numberposts'   => -1,
    'order'         => 'ASC',
    'orderby'       => 'meta_value',
    'meta_key'      => 'customer_first_name'
    'meta_query'    => array(
        'relation'      => 'OR',
        array(
            'key'           => 'customer_first_name',
            'value'         => $name,
            'compare'       => 'LIKE',
        ),
        array(
            'key'           => 'customer_last_name',
            'value'         => $name,
            'compare'       => 'LIKE',
        ),      
    ),  
);  

$customers = get_posts($args);

$num = count( $customers );

If i search only "John" results are showing up. If i search full name "John Doe" there are no results. Why is that?

  • You're doing a LIKE comparison, which means that both the first and last names need to match `%John Doe%, which isn't going to work because neither field has both names. – Jacob Peattie Aug 5 at 3:15
0
$name = 'John Doe';

// Split $name
$name = preg_split( '/\s+/', trim( $name ) );

// Set first name
$first_name = $name[0];

// Last name was provided?
$last_name = isset( $name[1] ) ? $name[1] : null;

// Define meta query args array
$meta_query_args = array();

// Set "first name" meta query or "first name" + "last name" if both exist
if ( is_null( $last_name ) ) {
    $meta_query_args[] = array(
        'key'     => 'customer_first_name',
        'value'   => $first_name,
        'compare' => 'LIKE',
    );
} else {
    $meta_query_args[] = array(
        'relation' => 'AND', // This is default, just trying to be descriptive
        array(
            'key'     => 'customer_first_name',
            'value'   => $first_name,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'customer_last_name',
            'value'   => $last_name,
            'compare' => 'LIKE'
        )
    );
}

// Set 'meta_query' in your $args variable
$args['meta_query'] = $meta_query_args;

Note that you'll have to add extra code to support "last name" + "first name" besides of "first name" + "last name" (order matters).

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.