概要
wp_list_pluck
関数は、配列内のオブジェクトまたは連想配列から特定の値だけを抽出するための便利な関数です。この関数は特に、データベースから取得したオブジェクトリストから特定のプロパティを抽出したい場合や、大量のデータを処理しやすくする際によく使われます。以下に、wp_list_pluck
関数が役立つシナリオをいくつか挙げます。
- 投稿のタイトルを一覧表示する際の抽出
- ユーザーのメールアドレスを一括処理する場合
- カスタムフィールドの値をまとめて取得する際
- タクソノミーの項目名を取得する場合
- プラグイン設定のキーを取得する際
- カスタム投稿タイプのスラッグを扱う場合
- メニュー項目のIDを集約する場合
- コメントの作者名を取得する際
構文
array wp_list_pluck( array $list, string $field, string|null $index_key = null )
パラメータ
$list
: 値として返したいオブジェクトまたは連想配列の配列。$field
: 抽出したいフィールドの名前。$index_key
: オプションで、返される配列のキーとして使用するフィールドの名前。
戻り値
指定されたフィールドの値のみを含む配列を返します。
関連する関数
使用可能なバージョン
この関数は、WordPress 3.1以降で使用可能です。
コアファイルのパス
wp-includes/general-template.php
サンプルコード
サンプルコード1: 投稿のタイトルを抽出する
このコードは、投稿のリストからタイトルのみを抽出し、配列として返します。
$posts = get_posts();
$titles = wp_list_pluck($posts, 'post_title');
引用元: https://developer.wordpress.org/reference/functions/get_posts/
サンプルコード2: ユーザーのメールアドレスを抽出する
この例では、全ユーザーのメールアドレスを取得して配列にします。
$users = get_users();
$user_emails = wp_list_pluck($users, 'user_email');
引用元: https://developer.wordpress.org/reference/functions/get_users/
サンプルコード3: コメントの著者名を取得する
コメントリストから著者名を取得するコードです。
$comments = get_comments();
$authors = wp_list_pluck($comments, 'comment_author');
引用元: https://developer.wordpress.org/reference/functions/get_comments/
サンプルコード4: カスタムフィールドの値を取得する
カスタムフィールドを持つ投稿から特定のフィールドを抽出する例です。
$posts = get_posts(['meta_key' => 'custom_field']);
$custom_values = wp_list_pluck($posts, 'custom_field');
引用元: https://developer.wordpress.org/reference/functions/get_posts/
サンプルコード5: タクソノミーの項目名を取得する
特定のタクソノミーから項目名を抽出する例です。
$terms = get_terms('category');
$term_names = wp_list_pluck($terms, 'name');
引用元: https://developer.wordpress.org/reference/functions/get_terms/
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |
非推奨または削除されたバージョン
wp_list_pluck
関数は、現在のところ非推奨または削除されていません。