Wordpress - Get post ids from WP_Query?

Use the fields argument in your query.

fields (string) - Which fields to return. All fields are returned by
default. There are two other options: - 'ids' - Return an array of post IDs. - 'id=>parent' - Return an associative array [ parent => ID, … ].

https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter

$latest = new WP_Query( array (
    'orderby'               => 'rand',
    'posts_per_page'        => 3,
    'fields' => 'ids'
));
var_dump($latest->posts);

Try

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

Read wp_list_pluck


Using the solution from @s-ha-dum is economical if you only need to get the id's, and you don't have previous query object set.

Here is why:

switch ( $q['fields'] ) {
    case 'ids':
        $fields = "$wpdb->posts.ID";
        break;
    case 'id=>parent':
        $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
        break;
    default:
        $fields = "$wpdb->posts.*";

Because in the case you only specify 'fields' => 'ids' nothing more you will get in return than the ID's.

If you would go with 'fields' => 'id=>parent' (Looks really funny) you will get also the parent ID's.

Any other way using 'fields' argument will not have any impact as of WordPress v4.7.

But in case you have the query as in the example wp_list_pluck will do the job.