Using wp list pluck to extract data from a WP Query Object
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.


