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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try
$post_ids = wp_list_pluck( $latest->posts, 'ID' );
Read wp_list_pluck
Method 2
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);
Method 3
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
Method 4
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.
Method 5
Why not use the get_the_ID() function? Just sharing the loop code and it shows all post ids in the query.
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_ID() . '</li>';
}
} else {
// no posts found
$string = "no posts found";
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0