Quantcast
Channel: WordPress – Alex's Blog
Viewing all articles
Browse latest Browse all 22

wp_list_pluck() Is An Awesome WordPress Function

$
0
0

If you’re a WordPress developer and you don’t know about wp_list_pluck(), then listen up!

Say you have an array called $posts that contains this:

[0] => stdClass Object
	[ID] => 675
	[post_author] => 5
	[post_date] => 2010-07-25 19:40:01
	[post_date_gmt] => 2010-07-25 19:40:01
	[post_content] => This site is using the standard ...
	[post_title] => About The Tests

[1] => stdClass Object
	[ID] => 501
	[post_author] => 6
	[post_date] => 2010-08-01 09:42:26
	[post_date_gmt] => 2010-08-01 16:42:26
	[post_content] => The last item in this page's content ...
	[post_title] => Clearing Floats

[2] => stdClass Object
	[ID] => 174
	[post_author] => 5
	[post_date] => 2007-12-11 16:25:40
	[post_date_gmt] => 2007-12-11 06:25:40
	[post_content] => Level 1 of the reverse hierarchy test ...
	[post_title] => Level 1
	)

[3] => stdClass Object
	[ID] => 173
	[post_author] => 5
	[post_date] => 2007-12-11 16:23:33
	[post_date_gmt] => 2007-12-11 06:23:33
	[post_content] => Level 2 of the reverse hierarchy test.
	[post_title] => Level 2

How would you go about getting all of the post_title values? Well obviously you could do something like this:

$post_titles = array();
foreach ( $posts as $key => $post ) {
	$post_titles[$key] = $post->post_title;
}

Sure, it’s not that complicated but that can get repetitive in your code. So how about this instead?

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

Much easier, right? :)

Thanks Michael Fields for reminding me about this great function!


Viewing all articles
Browse latest Browse all 22

Trending Articles