Question

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.

Was it helpful?

Solution

Try

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

Read wp_list_pluck

OTHER TIPS

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);

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.

I suggest this solution

get_posts([
  'posts_per_page' => -1,
  'post_status' => 'publish',
  'post_type' => 'some-custom-post-type',
  'fields' => 'ids',
]);

and as return you have array with ids inside ;)

array (size=5)
  0 => int 81002
  1 => int 77885
  2 => int 77180
  3 => int 74722
  4 => int 73312
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top