我正在尝试使用每个帖子的更改HTML内容制作一个自定义RSS feed。
在模板文件rss-custom.php
中,我有这个:
<?php while (have_posts()) : the_post(); ?>
<?php echo processPostContent(); ?>
<?php endwhile; ?>
在functions.php
中,有三个替换项,如下:
function processPostContent() {
$post = get_post(get_the_ID());
$post_content = strval($post->post_content);
// replace h3 and h4 tags with h2
$post_content = preg_replace('/<(\/?)h((?![12])\d)/im', "<$1h2", $post_content);
// strip every attribute of <img> other than src
$post_content = preg_replace('/<img[^>]*(src="[^"]*")[^>]*>/im', "<img $1 />", $post_content);
// insert text after some closing tags
$post_content = preg_replace('/<\/(h2|p|figure)>/im', "</$1><p>Inserted</p>", $post_content);
return $post_content;
}
然后我得到一个奇怪的结果:在20个帖子中,只有7-8个将被完全替换。其余的将获得前两个替代品,而不是第三个。有人知道为什么吗?
结果证明,该解决方案与循环或preg_replace
无关。某些帖子的内容不包含任何HTML标记,仅包含纯文本。这就是preg_replace
对它们没有任何影响的原因。但是,当这些内容在RSS feed中呈现时,将插入[[0 [自动])。这就是让我相信第三次替换被忽略的原因。
<p>
转向
First paragraph. Second paragraph.