You can use the post_count property of $WP_Query , for example:
$wp_query->post_count
Pay attention to the difference with found_posts , which counts messages that, although they correspond to the query, are not displayed (for example, for pagination). You might want to use one or another option depending on the specific situation.
source share