Quick way to pull a field from WP_Query

We all have come across having to pull out a list of post ids, or possibly some meta fields from a WP_Query result. The other day I found a really useful function in the codex called wp_list_pluck. I had never heard of this function before but it was so useful because it essentially replaces the foreach loop. Exploring the Codex always results in finding something of use, even if it’s not something you would use right away, but at least you can keep it in the back of your mind.

WP_Query

I went looking for something else was because I really was thinking of writing a function myself for this project. The idea was that I needed to build another query based on a list of ids. I didn’t want to have to a separate, but same query since I was already using the data from it. I also didn’t want to have an extra loop iterating over the same results again just to pull out the ids. Mainly because I knew that I was going to have to do this over and over again.

wp_list_pluck

I went to the Codex first to see if there was possibly anything more concise that I could use that would work. Well after about 5-10 mins, I found wp_list_pluck(). The Codex describes it by “Pluck a certain field out of each object in a list.” Perfect!

Here’s the sample that the codex has:
[code lang=”php”]
$foods = array(
array(
‘name’ => ‘Banana’,
‘color’ => ‘Yellow’,
),
array(
‘name’ => ‘Apple’,
‘color’ => ‘Red’,
),
array(
‘name’ => ‘Lettuce’,
‘color’ => ‘Green’,
),
array(
‘name’ => ‘Apple’,
‘color’ => ‘Red’,
),
);
$food_names = wp_list_pluck( $foods, ‘name’ );
[/code]
$food_names now has a numeric indexed array of food names
[code lang=”php”]
$food_names => array(
‘Banana’,
‘Apple’,
‘Lettuce’,
‘Apple’
);
[/code]
Another golden nugget!

/ Jason Resnick

Jason is a WordPress developer helping small businesses, design and marketing agencies achieve their goals by specializing in Ecommerce and increasing conversions. Learn more about him here.

More Posts | Twitter | Work ON Your Business Challenge | Coaching

Leave a Comment

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