Inside the loop, as michael pointed out you could just refer to $numpages
global variable.
Outside of the loop, your code is almost fine.
Being the number of the pages the number of <!--nextpage-->
+ 1, you could save a function call by doing:
$numOfPages = 1 + substr_count($the_post->post_content, '<!--nextpage-->');
As a quick and not-that-dirty solution that is totally fine.
However, that code would not take into account filters and other minor things (e.g. <!--nextpage-->
at the very start of the post content is ignored).
So to be 100% compatible with core code, your function should be something like:
function count_post_pages($post_id) {
$post = get_post($post_id);
if (!$post) {
return -1;
}
global $numpages;
$q = new WP_Query();
$q->setup_postdata($post);
$count = $numpages;
$q->reset_postdata();
return $count;
}
This is 100% compatible with core code, but also is more "expensive" and triggers more hooks than you actually need (with possibly unexpected side effects).
The third solution would be:
function count_post_pages($post_id) {
$post = get_post($post_id);
if (!$post) {
return -1;
}
$content = ltrim($post->post_content);
// Ignore nextpage at the beginning of the content
if (strpos($content, '<!--nextpage-->') === 0) {
$content = substr($content, 15);
}
$pages = explode('<!--nextpage-->', $content);
$pages = apply_filters('content_pagination', $pages, $post);
return count($pages);
}
This solution is relatively "cheap" and it is 100% core compliant... for now, in fact, the issue with this code is that it duplicates some code that might change in future versions (e.g. the "content_pagination" filter was added in version 4.4, so quite recently).