WordPress中统计含多ACF区块的文章字数问题
WordPress单篇文章含ACF区块的总字数统计方案
问题背景
要统计WordPress单篇指定文章的总字数,仅用str_word_count(the_content())只能统计默认文章内容,无法覆盖通过get_template_part引入的ACF布局区块内容。尝试在app/builder.php中统计区块字数,但不知道如何将结果传回single.php汇总,同时还存在嵌套ACF布局(如car_details下的子项)的内容统计问题。
解决方案
1. 将ACF区块统计逻辑封装为可返回值的函数
修改app/builder.php,把字数统计逻辑封装成函数,让single.php可以直接调用获取统计结果:
// app/builder.php function get_acf_layouts_word_count() { $total_words = 0; if (have_rows('layouts')) : while (have_rows('layouts')) : the_row(); // 处理基础content字段 if ($content = get_sub_field('content')) { $total_words += str_word_count(strip_tags($content)); } // 处理嵌套布局:比如car_details类型 if (get_row_layout() === 'car_details') { if ($cars = get_sub_field('cars')) { foreach ($cars as $car) { // 统计car的name和content if (!empty($car['name'])) { $total_words += str_word_count($car['name']); } if (!empty($car['content'])) { $total_words += str_word_count(strip_tags($car['content'])); } } } } // 可继续添加其他布局类型的处理逻辑 // if (get_row_layout() === 'other_layout') { ... } endwhile; endif; return $total_words; }
2. 在single.php中汇总总字数
在single.php中,先获取默认文章内容的字数,再调用上面的函数获取ACF区块的字数,两者相加得到总字数:
// single.php // 先获取默认文章内容的字数(注意用get_the_content()而非the_content(),后者直接输出内容) $content_words = str_word_count(strip_tags(get_the_content())); // 引入builder.php(如果之前没自动加载的话) get_template_part('app/builder'); // 获取ACF区块的字数 $acf_layouts_words = get_acf_layouts_word_count(); // 总字数 $total_word_count = $content_words + $acf_layouts_words; // 输出总字数(按需使用) echo "文章总字数:{$total_word_count}";
关键说明
- 使用
strip_tags()是为了去除内容中的HTML标签,避免统计标签字符;如果需要保留HTML内的文本统计,可根据需求调整。 - 针对不同的ACF布局类型(如示例中的
car_details),需要单独处理其嵌套字段,确保所有文本内容都被统计到。 get_the_content()用于获取文章内容的字符串,而the_content()会直接输出内容,不能用于str_word_count()的参数。
内容的提问来源于stack exchange,提问作者Álvaro
相关产品推荐
相关产品推荐

