我试图制作一个自定义RSS ,并对每个帖子的HTMLContent做一些修改。
在模板文件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个将被完全取代。剩下的人得到前两个替代者,而不是第三个。有人知道为什么吗?
发布于 2019-12-05 10:36:48
结果,这个解决方案与循环和preg_replace没有任何关系。有些帖子的内容不包括任何HTML标签,只包含纯文本。这就是为什么preg_replace对他们没有任何影响的原因。但是,当这些内容在RSS中呈现时,<p>标记将自动插入。所以我才相信第三个替补被跳过了。
First paragraph.
Second paragraph.转到
<p>First paragraph.</p>
<p>Second paragraph.</p>https://stackoverflow.com/questions/59191669
复制相似问题