Let current user know pending posts counts using wp_query

I'm working on a query to let a logged-in user know if the user has more than 5 pending posts. Here's what I ended up with:

// Start the query
$query = new WP_Query( array(
    'post_type'      = 'post',
    'author'         = get_current_user_id(),
    'post_status'    = 'pending',
    'posts_per_page' = -1
));

// Start the loop
if ( $query-have_posts() ) {

    if ( $query-found_posts = 5 ) {
        echo '5 or more pending posts';
    } else {
        echo 'Less than 5 pending posts';
    }

    wp_reset_postdata();

} else {
    echo 'Nothing found!';
}

It seems working. Is there anything missing? Is there anything to correct?

Topic functions wp-query php Wordpress

Category Web


As others have already noted in the comments, using "posts_per_page" => 5, is better option than "posts_per_page" => -1, for your query as it will give you the information you need for your conditional check.

Limiting what is queried is also something to consider - as honk31 mentioned. Along 'fields' => 'ids' you can also add the following lines to your query.

  • 'no_found_rows' => true - number of total rows not needed in this case
  • 'update_post_meta_cache' => false - meta not needed in this case
  • 'update_post_term_cache' => false - terms not needed in this case

The $query->have_posts() with wp_reset_postdata(); is also a bit unnecessary as you can just use $query->found_posts or ->post_count directly.

if ( $query->found_posts ) {
  echo $query->found_posts >= 5 ? '5 or more pending posts' : 'Less than 5 pending posts';
} else {
  echo 'Nothing found!';
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.