阅读更多(<!--more-->
) 标记由处理get_the_content()
在里面wp-includes/post-template.php
. 它不会对其内容输入运行任何可挂接的过滤器;然而,这来自$pages
全局,可在设置时通过挂接the_post
行动
以下功能将自动插入<!--more-->
在280个字符后的第一个空格处进行标记(跳过HTML标记,并将空格序列作为单个字符进行计数),如果尚未存在:
\\add_action(
\'the_post\',
function($post, $query) {
global $pages, $shortcode_tags;
// Matches an HTML entity, block of whitespace, or single character:
static $rxChar = \'&#?+\\\\w++;|\\\\s++|[^<]\';
// Matches an HTML tag:
static $rxTag = \'<[^>]*+>\';
// Based on regex in from `get_shortcode_regex`
$tagnames = \\array_keys($shortcode_tags);
$tagregexp = \\join(\'|\', \\array_map(\'preg_quote\', $tagnames));
$rxShortcode =
\'\\\\[\' // Opening bracket
. \'\\\\[?+\' // 1: Optional second opening bracket for escaping
. \'(?&shortcode_tag)\' // 2: Shortcode name
. \'(?![\\\\w-])\' // Not followed by word character or hyphen
. \'[^\\\\]\\\\/]*+\' // Not a closing bracket or forward slash
. \'(?:\'
. \'\\\\/(?!\\\\])\' // A forward slash not followed by a closing bracket
. \'[^\\\\]\\\\/]*+\' // Not a closing bracket or forward slash
. \')*+\'
. \'\\\\/?+\' // 4: Self closing tag ...
. \'\\\\]\' // ... and closing bracket
. \'\\\\]?+\'; // 6: Optional second closing brocket for escaping
// Matches zero or more HTML tags or shortcode tags
$rxTags = "(?:$rxTag|$rxShortcode)*+";
$regex = "/(?(DEFINE)(?<shortcode_tag>$tagregexp)(?<char>$rxChar)"
. "(?<tags>$rxTags))"
// At least 280 characters, from the start, followed by a space
// (catastrophic failure with general repetition quantifier mitigated
// against by splitting into two multiplicative repetitions):
. \'^(?:(?:(?&tags)(?&char)){10}+){28}+(?&tags)(?:(?&char)(?&tags))*?\'
. \'(?=\\\\s)/u\';
foreach ($pages as $i => $page) {
if (\\strpos($page, \'<!--more\') === false) {
$page = \\preg_replace($regex, \'$0<!--more-->\', $page, 1);
if ($page !== null) {
$pages[$i] = $page;
} else {
trigger_error(
"Regex failure inserting \'Read More\' tag into `$pages[$i]`."
);
}
}
}
},
10, 2
);
这应该是不言自明的,不过我会在regex上添加一些注释:
在u
(UTF-8)修饰符确保多字节字符只计数一个
+
(所有格)量词massively optimizes the
performance and memory footprint (其中令牌不能使用以下任何令牌)。然而,当应用于一般的重复量词时,它似乎与失败没有多大区别,因此这被分为重复的重复。尽管如此,如果失败,内容将保持不变?
(lazy)quantifier确保280个字符后的第一个空格停止在,而不是最后一个(我知道这个问题是4年前提出来的,但一直没有得到回答;我发现它在寻找完全相同的解决方案,而我在其他地方找不到。)