【发布时间】:2015-12-31 17:51:39
【问题描述】:
我需要转换 the_content(); 返回的 HTML 字符串;在 Wordpress 中到每个父级元素的数组。例如:
<h3>My subtitle</h3>
<p>Some content here</p>
<blockquote><p>A blockquote goes here</p></blockquote>
会变成:
array['<h3>My subtitle</h3>', '<p>Some content here</p>', '<blockquote> <p>A blockquote goes here</p></blockquote>']
我们要这样做的原因是在内容中插入广告 - 如果第一段或内容块大于 670 个字符,则在第一段之后,如果内容短于该长度,则在第二段之后。挑战在于这些段落中的任何一个是否被另一个元素包裹,或者是否涉及另一个元素。
这是我目前拥有的代码:
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);
$firstParagraphLength = strlen($content[0]);
if($firstParagraphLength > 670) {
$paragraphAdAfter = 1;
} else {
$paragraphAdAfter = 2;
}
// If this is after the target paragraph, insert ad code first
for ($i = 0; $i <count($content); $i++) {
if ($i == $paragraphAdAfter) { ?>
<!-- AD CODE -->
My ad code goes here, great!
<?php
}
echo $content[$i] . "</p>";
} ?>
这确实有效,但如果第一段或第二段中包含块引用,则广告将插入块引用元素中。数据是非常动态的,所以我需要想办法根据父级元素进行拆分,无论它们是块引用、段落、标题等。
【问题讨论】:
-
使用 domdocument:secure.php.net/manual/en/class.domdocument.php
-
您是否考虑过 Shortcode API 以便内容作者可以决定广告的放置位置?
-
另外,如果您不指定这是插件还是主题,我们将无法在此处提供答案。您可能还想查看wordpress.stackexchange.com,它非常丰富,内容丰富。
-
@Volomike,可以使用核心 PHP 代码。看看吧!
-
@Venkatraman 谢谢,检查一下!有点困惑,但我会试一试