LoginSignup
2
2

More than 5 years have passed since last update.

wordpressのユーザー検索でsearchとmetaを同時に使いたい

Posted at

問題点

wordpressで公開側でユーザー検索とその一覧を出すときに、WP_User_Queryを使って出力をするのですが、
この際、

// The search term
$search_term = 'Ross';

// WP_User_Query arguments
$args = array (
    'role' => 'reporter',
    'order' => 'ASC',
    'orderby' => 'display_name',
    'search' => '*'.esc_attr( $search_term ).'*',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'first_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'last_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key' => 'description',
            'value' => $search_term ,
            'compare' => 'LIKE'
        )
    )
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);

// Get the results
$authors = $wp_user_query->get_results();

// Check for results
if (!empty($authors)) {
    echo '<ul>';
    // loop trough each author
    foreach ($authors as $author)
    {
        // get all the user's data
        $author_info = get_userdata($author->ID);
        echo '<li>'.$author_info->first_name.' '.$author_info->last_name.'</li>';
    }
    echo '</ul>';
} else {
    echo 'No authors found';
}

(https://wpdocs.osdn.jp/%E3%82%AF%E3%83%A9%E3%82%B9%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/WP_User_Queryより引用)

をつかうと、
メールアドレスなどから表示するsearchと、
first_nameなどから表示するmeta_queryとで
ガッチャンコしてうまく出力されないようです。
(例:sample@example.comのユーザーを検索しても表示されない)

解決策

searchの検索とmeta_queryの検索を分けて、マージをして出力する。

$q1 = get_posts(array(
        'post_type' => 'post',
        's' => $query
));

$q2 = get_posts(array(
        'post_type' => 'post',
        'meta_query' => array(
            array(
               'key' => 'speel',
               'value' => $query,
               'compare' => 'LIKE'
            )
         )
));

$merged = array_merge( $q1, $q2 );

$post_ids = array();
foreach( $merged as $item ) {
    $post_ids[] = $item->ID;
}

$unique = array_unique($post_ids);

$posts = get_posts(array(
    'post_type' => 'posts',
    'post__in' => $unique,
    'post_status' => 'publish',
    'posts_per_page' => -1
));

if( $posts ) : foreach( $posts as $post ) :
     setup_postdata($post);

     // now use standard loop functions like the_title() etc.     

enforeach; endif;

(http://wordpress.stackexchange.com/questions/78649/using-meta-query-meta-query-with-a-search-query-sより引用)

ポイントは$q1$q2とでそれぞれ出力して、array_margeで1つにまとめてしまうこと。

おそらくここらへんは不具合な気もするのでのちのち治るかと思うのですが、
治ったあとでも、この方法なら不具合も出ないと思うのでしばらくはこれで対応してみてはいかがでしょうか。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2