Pluck and Filter Arrays in WordPress

WordPress has a few lesser known utility functions for operating on arrays in a few specific ways.

These lesser known functions, available in WordPress core, can enhance your code clarity and brevity when either of their specific use case comes up.

For the examples we'll be using the following dataset.

<?php

$people = array(
  array(
    'id' =>  1,
    'name' => 'Jon',
    'favorite_color' => 'red',
  ),
  array(
    'id' => 2,
    'name' => 'Frank',
    'favorite_color' => 'blue',
  ),
  array(
    'id' => 3,
    'name' => 'Bill',
    'favorite_color' => 'red',
  ),
  array(
    'id' => 4,
    'name' => 'James',
    'favorite_color' => 'green',
  ),
  array(
    'id' => 5,
    'name' => 'Nathan',
    'favorite_color' => 'blue',
  ),
);

wp_list_pluck()

wp_list_pluck($array, 'key') allows you to extract a specific key from all associative arrays or objects within an array.

For example if we just wanted an array of the $people's names.

<?php

$names = wp_list_pluck($people, 'name');
// array('Jon', 'Frank', 'Bill', 'James', 'Nathan');

If you didn't know this function existed, you'd likely end up writing a foreach loop and doing the work yourself when you could accomplish this common goal in a single line.

wp_list_filter()

wp_list_filter($array, $criteria[, $operator]) is a bit more complex and it allows you to specify some criteria to generate a subset of your array of data.

Lets select all the people whose favorite color is blue

<?php

$criteria = array('favorite_color' => 'blue');
$blue_lovers = wp_list_filter($people, $criteria);

Would result in

<?php

array(
    array(
        'id' => 2,
        'name' => 'Frank',
        'favorite_color' => 'blue',
    ),
    array(
        'id' => 5,
        'name' => 'Nathan',
        'favorite_color' => 'blue',
    ),
);

You can also specify the type of conditional operator you'd like to use when specifying multiple criteria. The available operators are 'AND', 'OR', and 'NOT'. They work as you would expect, matching all, any, or none of the criteria. The default operator is 'AND'.

<?php

$criteria = array('favorite_color' => 'green');
$not_green = wp_list_filter($people, $criteria, 'NOT');

Would result in

<?php

array(
  array(
    'id' => 1,
    'name' => 'Jon',
    'favorite_color' => 'red',
  ),
  array(
    'id' => 2,
    'name' => 'Frank',
    'favorite_color' => 'blue',
  ),
  array(
    'id' => 3,
    'name' => 'Bill',
    'favorite_color' => 'red',
  ),
  array(
    'id' => 5,
    'name' => 'Nathan',
    'favorite_color' => 'blue',
  ),
);

Another situation where you could clearly do this yourself, but your code clarity and brevity could benefit from this one line solution.