How do I extract just the post ID of the first item in whatever WP_Query returns? All the examples, answers, and documentation that I have seen dives off into doing things with loops. That's nice, but I just want the first ID. Nothing else. As the plugin will only ever generate a custom post type when there is none, the user should only have one. I need to get the ID of that post.
How do I find a post ID? Is there an easier way to find out if the user has a post available?
This is as far as I have gotten:
$query = new WP_Query( array(
'author' => $current_user,
'post_type' => 'my_custom_post_type',
// etc.
) );
$author_posts = new WP_Query( $query );
if( $author_posts->have_posts() ) {
// They have at least one. Grovey, now what?
}
unset($author_posts);
How do I extract just the post ID of the first item in whatever WP_Query returns? All the examples, answers, and documentation that I have seen dives off into doing things with loops. That's nice, but I just want the first ID. Nothing else. As the plugin will only ever generate a custom post type when there is none, the user should only have one. I need to get the ID of that post.
How do I find a post ID? Is there an easier way to find out if the user has a post available?
This is as far as I have gotten:
$query = new WP_Query( array(
'author' => $current_user,
'post_type' => 'my_custom_post_type',
// etc.
) );
$author_posts = new WP_Query( $query );
if( $author_posts->have_posts() ) {
// They have at least one. Grovey, now what?
}
unset($author_posts);
Share
Improve this question
asked Jul 7, 2019 at 12:55
Matthew Brown aka Lord MattMatthew Brown aka Lord Matt
1,0683 gold badges13 silver badges34 bronze badges
3
|
2 Answers
Reset to default 1If you only need the ID of a single post of a custom post type, to see if it exists, I'd suggest just using get_posts()
with fields
set to ids
:
$post_ids = get_posts(
[
'numberposts' => 1,
'author' => $current_user,
'post_type' => 'my_custom_post_type',
'fields' => 'ids',
]
);
if ( isset( $post_ids[0] ) ) {
$post_id = $post_ids[0];
}
However, if you have a post type where every user gets 1 post, I'd suggest storing the ID of their post as user meta. Then you don't need to bother with this sort of query:
$post_id = get_user_meta( $current_user, 'the_post_type', true );
If you are trying to get the number of posts the user has authored in your custom post type then you need to do the following:
$post_type = '<YOU_CUSTOM_POST_TYPE_SLUG>';
$user_post_count = count_user_posts( $userid , $post_type );
if ($user_post_count == 0) {
//Do Something
}
WP_Query::$posts
. E.g.$post_id = ( ! empty( $query->posts ) ) ? $query->posts[0]->ID : 0;
– Sally CJ Commented Jul 7, 2019 at 13:24