概要
acf/fields/user/query は、Advanced Custom Fields (ACF) において、ユーザーフィールドのクエリをカスタマイズするためのフィルタです。このフィルタを利用することで、特定の条件に基づいてユーザーを絞り込んだり、表示内容を変更したりできます。各ユーザーのテキストを表示するために WP_Query によって使用されるクエリ $args をフィルタリングします。
よく使われる機能
- 特定の役割を持つユーザーを取得
- ユーザー名に基づく検索機能の実装
- ユーザーのメタデータに基づくフィルタリング
- ユーザーのステータス(アクティブ/非アクティブ)による絞り込み
- カスタムクエリを用いて特定の条件を満たすユーザーをリストアップ
- 検索結果の表示順のカスタマイズ
構文
add_filter('acf/fields/user/query', 'your_custom_function', 10, 3);
パラメータ
$args:WP_User_Queryに渡される引数の配列$field: フィールドの設定$post_id: 現在の投稿のID
戻り値
カスタマイズされた $args 配列が戻り値となり、これによりカスタムユーザークエリが実行されます。
使用可能なバージョン
- ACFバージョン: 5.0以上
- WordPressバージョン: 4.0以上
この関数のアクションでの使用可能性
| アクション | 使用例 |
|---|---|
| mu_plugin_loaded | |
| registered_post_type | |
| plugins_loaded | |
| wp_roles_init | |
| setup_theme | |
| after_setup_theme | |
| set_current_user | |
| init | |
| register_sidebar | |
| wp_loaded | |
| send_headers | |
| parse_query | |
| pre_get_posts | |
| wp | |
| template_redirect | |
| get_header | |
| wp_head |
サンプルコード
サンプル1: 特定の役割を持つユーザーを取得
このコードは、特定の役割(例: ‘editor’)を持つユーザーのみを表示するために、クエリをフィルタリングします。
add_filter('acf/fields/user/query', function($args, $field, $post_id) {
$args['role'] = 'editor';
return $args;
});
サンプル2: ユーザー名による検索機能の実装
このコードは、ユーザーのログイン名に基づいて検索結果を制限します。
add_filter('acf/fields/user/query', function($args, $field, $post_id) {
$args['search'] = 'john'; // ユーザー名に'john'を含むユーザーを検索
return $args;
});
サンプル3: ユーザーメタデータに基づくフィルタリング
このサンプルでは、ユーザーのメタデータ(例: ‘city’)に基づいてクエリをフィルタリングしています。
add_filter('acf/fields/user/query', function($args, $field, $post_id) {
$args['meta_query'] = array(
array(
'key' => 'city',
'value' => 'Tokyo',
'compare' => 'LIKE'
)
);
return $args;
});
サンプル4: 特定の条件を満たすユーザーをリストアップ
このコードは、カスタム条件に合ったユーザーをリストするためのクエリをフィルタリングします。
add_filter('acf/fields/user/query', function($args, $field, $post_id) {
$args['meta_query'] = array(
array(
'key' => 'membership_status',
'value' => 'active',
'compare' => '='
)
);
return $args;
});
サンプル5: 結果の表示順のカスタマイズ
このサンプルでは、取得したユーザーを名前のアルファベット順に並べ替える方法を示しています。
add_filter('acf/fields/user/query', function($args, $field, $post_id) {
$args['orderby'] = 'display_name'; // 表示名で並べ替え
$args['order'] = 'ASC';
return $args;
});