Using wp list pluck to extract data from a WP Query Object

By North Street, A Creative Studio

Often times, you’ll need to run a WP_Query, but don’t actually need the whole object it returns. Perhaps just the post id’s are all you want.

Previously, I’d take the object, then use a foreach to loop through it, building the array of id’s that I need.

But I’ve just discovered wp_list_pluck which makes this way simpler:

$latest = new WP_Query( array (
	'post_type' => array('post'),
	'posts_per_page'	=> 3
));

$post_ids = wp_list_pluck( $latest->posts, 'ID' );

….and that’s it. $post_ids will now be an array of ids.

Array
(
    [0] => 8473
    [1] => 5152
    [2] => 1343
)

Sweet.

 

About north street

We engineer the thoughtful transformation of great organizations. Our proven process helps us understand what your competitors are doing right — and wrong. Want to learn more? Let’s chat.

More Notes

A bowler hat with radio waves behind it

From Layoff to Leadership: Tom Conlon’s Journey to a Prosperous Business

Welcome to Your 2024 Branding Pep Talk

A bowler hat with radio waves behind it

CEO Tom Conlon talks shop on Podcast Marketing Secrets