如何高效获取当前WordPress单篇文章的页数?
Hey there! I totally get the pain of processing huge posts by splitting the entire $post_content every time to count pages from <!--nextpage--> tags—it’s a huge waste of memory and slows things down. Since the WP_Post class doesn’t have a built-in property for this, let’s go over some smarter, more efficient approaches:
1. Fast String Count (Best for Standard Tags)
If your <!--nextpage--> tags are consistently formatted (no extra spaces or variations), use substr_count()—it’s lightning fast because it just scans the string for exact matches without creating a massive array:
// Get the number of nextpage tags, add 1 for the initial page $page_count = substr_count( $post->post_content, '<!--nextpage-->' ) + 1;
This uses minimal memory even for ultra-long posts, since it doesn’t split the content into chunks.
2. Flexible Regex Match (Handles Tag Variations)
If you need to account for variations like <!-- nextpage --> (with spaces), <!--NEXTPAGE--> (uppercase), or other whitespace tweaks, use preg_match_all() with a flexible pattern:
// Match any case of nextpage with optional whitespace around the tag text preg_match_all( '/<!--\s*nextpage\s*-->/i', $post->post_content, $matches ); $page_count = count( $matches[0] ) + 1;
This is still way more efficient than splitting the full content, as it only captures the matches instead of splitting the entire post into an array.
Why This Beats Splitting Content
Splitting large $post_content with explode() or similar creates an array where each element is a full page of content. For posts with hundreds of pages, this eats up tons of memory and slows down your site. Counting matches instead only traverses the string once, keeping memory usage low and performance snappy.
内容的提问来源于stack exchange,提问作者Ivan Cachicatari

