Function: wp_list_pluck

wp_list_pluck allows you to extract a specific field out of a multi-dimension array or object in a list.

One example of a use case would be while getting the taxonomies that are associated with a specific post.

$post = get_post( $post_id );
$taxonomies = get_object_taxonomies( $post, 'names' );

When examining the contents of $taxonomies, you would get something along the lines of:

array(2) {
     [0]=> string(6) "category-1" 
     [1]=> string(10) "category-2" 
}

One way to handle this would be to write a foreach loop to proceed through all the elements.

$taxonomies_list = array();
foreach( $taxonomies as $taxonomy ) {
     $taxonomies_list[] = $taxonomy->slug;
}

However, wp_list_pluck accomplishes the same thing but in a more concise fashion! Depending on your use case, this could help keep your code extra-tidy.

$taxonomies_list = wp_list_pluck( $taxonomies, 'slug' );
Additional Reading:

Leave a Reply

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