Pluck a certain field out of each object in a list
<?php wp_list_pluck( $list, $field, $index_key = null ); ?>
The following is an array listing foods:
<?php $foods = array( array( 'id' => 4, 'name' => 'Banana', 'color' => 'Yellow', ), array( 'id' => '5', 'name' => 'Apple', 'color' => 'Red', ), array( 'id' => 2, 'name' => 'Lettuce', 'color' => 'Green', ), array( 'id' => '7', 'name' => 'Apple', 'color' => 'Red', ), ); ?>
The names of each food can easily be "plucked" from the $foods array using
wp_list_pluck()
.
<?php $food_names = wp_list_pluck( $foods, 'name' ); ?>
$food_names
will now contain a numerically indexed array of food names equivalent to:
<?php array( 'Banana', 'Apple', 'Lettuce', 'Apple' ); ?>
Since version 4.0 you may define a third parameter named $index_key
to define a specific field of the list to be used as key. The following snippet would get listings in the form of id => name
.
<?php $food_names = wp_list_pluck( $foods, 'name', 'id' ); ?>
The resulting $food_names
array:
<?php array( 4 => 'Banana', 5 => 'Apple', 2 => 'Lettuce', 7 => 'Apple' ); ?>
Since: 3.1
wp_list_pluck() is located in wp-includes/functions.php