Get post ids from WP_Query?

Is there a way I can retrieve an array of post ids queried from the following:

$latest = new WP_Query( array (
    'orderby'               => 'rand',
    'posts_per_page'        => 3
));

if ( $latest -> have_posts() ) : while ( $latest -> have_posts() ) : $latest -> the_post();

    get_template_part( 'templates/content', 'post' );

endwhile; endif; wp_reset_postdata();

Follow Up:

I used wp_list_pluck to retrieve an array of post ids:

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

Then converted the array into a string using the implode function:

$post_ids_string = implode( ',', $post_ids );

Sorry for the ambiguous question.

5

Try

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

Read wp_list_pluck

Leave a Comment