使用WP_User_Query进行名字和姓氏搜索

时间:2016-12-04 06:14:27

标签: php mysql wordpress

我正在尝试开发目录搜索。以下工作正常用于姓氏搜索。但是,我需要上一个和第一个名字一起搜索。我怎样才能做到这一点:

function dispDirectory()
{
  global $user_ID;

  // Disallow directory if there is a messaging administrator and this person is not it.
  if ($this->admin_user_id && $this->admin_user_id != $user_ID) {
    return '';
  }

    $directory = "<form name='form' method='post'><label for='clientname'>Client Name: </label>
    <input name='clientname' id='clientname' type='text' style='width: 181px;'
    value=''/><input type='submit'></form>";

    $clientname= $_POST["clientname"];

    $search_string = $clientname;

    $args  = array(
        'meta_key' => 'last_name',
        'meta_compare' => 'like',
        'meta_value' => $search_string,
    );

    $wp_user_query = new WP_User_Query($args);
    $wp_user_query->query_orderby = str_replace( 'user_login', 'wp_usermeta.meta_value', $wp_user_query->query_orderby );
    $wp_user_query->query();

    $users = $wp_user_query->get_results();


  foreach($users as $u)
  {
    $firstName = get_user_meta($u->ID, 'first_name', true);
    $lastName = get_user_meta($u->ID, 'last_name', true);         

    $directory .= '<p><strong>'.$lastName.', '.$firstName.'</strong> - <a href="'.$this->actionURL.'newmessage&to='.$u->ID.'">'.__('Send Message', 'cartpaujpm').'</a></p>';
  }
  return $directory;
}

2 个答案:

答案 0 :(得分:2)

您可以搜索多个元字段,例如下面的元查询

$args  =  array ( 
        'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'first_name',
            'value'   => $search_string,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'last_name',
            'value'   => $search_string,
            'compare' => 'LIKE'
        )
        )
    );

答案 1 :(得分:0)

我最近遇到了类似的问题。按名称搜索并需要检查:

wp_users表:

  • 显示名称,

wp_usermeta表:

  • 名字
  • 姓氏

我要做的是将输入的搜索结果分成一个数组,然后检查每个部分:

if( ! empty( $searchword ) ){

    $parts = explode( ' ', $searchword );

    $qv['search_columns'] = array( 'display_name' );
    $qv['search'] = "*{$searchword}*";
    $qv['orderby']  = 'display_name';
    $qv['order']    = 'ASC';

    if( ! empty( $parts ) ){

        $qv['meta_query'] = [];
        $qv['meta_query']['relation'] = 'OR';

        foreach( $parts as $part ){
            $qv['meta_query'][] = array(
                'key'     => 'first_name',
                'value'   => $part,
                'compare' => 'LIKE'
            );
            $qv['meta_query'][] = array(
                'key'     => 'last_name',
                'value'   => $part,
                'compare' => 'LIKE'
            );
        }

    }

};

因此,通过类似“ John Smith” 的搜索,我们将“ John Smith”作为用户的display_name,将“ John”作为first_name或{{1 }},而“史密斯”(Smith)为last_namefirst_name

法典上有一个类似的示例:https://codex.wordpress.org/Class_Reference/WP_User_Query#Examples