0

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);
  • 1
    Use WP_Query::$posts. E.g. $post_id = ( ! empty( $query->posts ) ) ? $query->posts[0]->ID : 0; – Sally CJ Jul 7 at 13:24
  • Are you trying to allow user to post to cpt only if they have never posted before? – Faham Shaikh Jul 7 at 13:59
  • I'm going to link to the post if it exists and if not make it then link to it. – Matthew Brown aka Lord Matt Jul 7 at 14:41
1

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

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.