Using the wp_list_pluck() WordPress Function

The 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.

Function Overview

wp_list_pluck ( array $list, int|string $field, int|string $index_key = null )

$list
(array) (Required) — List of objects or arrays

$field
(int|string) (Required) — Field from the object to place instead of the entire object

$index_key
(int|string) (Optional) — Field from the object to use as keys for the new array.

Sample Usage

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',
)

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.