You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效获取当前WordPress单篇文章的页数?

Efficient Ways to Count WordPress Post Pages Without Splitting Full Content

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:53:28