Function: wp_list_pluck()

Suppose you want to get some information about some posts in this format: an array of post titles, keyed by the post ID. How would you do it? Spoiler alert: Skip the first 2 options

Let’s assume you’re fetching some posts via get_posts(). For simplicity I won’t be passing an arguments to that function, but go ahead if you want to 🙂

$posts = get_posts();

Option 1

$post_titles = array();

foreach( $posts as $p ) {
	$post_titles[ $p->ID] = $p->post_title;
}

Not bad, but surely there’s a WordPress-y way to do that.

Option 2

You might have come across the function wp_list_pluck() which is really neat for pulling a particular value by key from an array of arrays or objects.

$post_titles = wp_list_pluck( $posts, 'post_title' );

This works for getting the titles, but leaves us without the IDs as keys. You might extrapolate that to this

$post_titles = array_combine( wp_list_pluck( $posts, 'ID' ), wp_list_pluck( $posts, 'post_title' ) );

Now we have what we want, but that seems clunky.

Option 3 (the best!)

Since WordPress 4.0, wp_list_pluck() takes a third argument that makes it behave more like the native PHP function (since 5.5) array_column(). This third argument allows you to specify a key whose value should be used as the key of the returned array.

$post_titles = wp_list_pluck( $posts, 'post_title', 'ID' );

Leave a Reply

Your email address will not be published. Required fields are marked *