Want to shorten your WordPress Code, use wp_list_pluck. It’s an amazing function!

If you have ever developed a WordPress Theme or Plugin, I am sure you must have dealt with Queries and Objects. A lot of Information needs to be extracted from these objects to use them in Themes/Plugins. To extract this information, the go-to weapon in PHP is the foreach tool. Every value of an object can be accessed easily using the foreach loop. If you are familiar with the concept of Queries and the array of posts it provides, I am sure that at some point or another, you would have used foreach in your coding lifecycle.

But sometimes using the foreach can be an annoyance. Afterall, the code does get rather dirty and sometimes even become incomprehensible. Also, if you want an array of a value from all the objects, it is a rather cumbersome code including a foreach and a counter. Here is where, wp_list_pluck comes in.

This function essentially does what foreach does, only much more efficiently. Here is the official description of the wp_list_pluck function-

[su_quote]Pluck a certain field out of each object in a list[/su_quote]

It literally plucks out a value from the object and returns it in the form of an array. All this with just a single line. I found out about this function just a few days ago and since then I have been rebuking myself for using foreach all these years. Undoubtedly foreach has its advantages but for the WordPress scenario, wp_list_pluck is definitely the better of the two.

Leave a comment

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