wp_list_pluck() WordPress function makes it easy to convert an array of items (objects or arrays) to an array of values. It will loop through all the items in the array and replace the item with a specific field value from the item.
wp_list_pluck ( array $list, int|string $field, int|string $index_key = null )
(array) (Required) — List of objects or arrays
(int|string) (Required) — Field from the object to place instead of the entire object
(int|string) (Optional) — Field from the object to use as keys for the new array.
Let’s say we have a list of posts (simplified for demo purposes):
$list = array( array( 'ID' => 1, 'post_title' => 'Hello World', ), array( 'ID' => 2, 'post_title' => 'Sample Page', ), );
If we want to extract just the post titles from this list, then we could simply do this:
wp_list_pluck( $list, 'post_title' );
The value returned would then be an array of the post titles:
array( 'Hello World', 'Sample Page' );
If we wanted to extract the post titles, but use the post IDs as the array indices, then we just need to use the third parameter:
wp_list_pluck( $list, 'post_title', 'ID' );
The value returned would then be an array of the post titles indexed by post ID:
array( 1 => 'Hello World', 2 => 'Sample Page', )