【发布时间】:2013-04-23 22:03:17
【问题描述】:
虽然这是面向 Wordpress 的,但我认为 PHP 的基础更多的是 Stackoverflow 问题:
我想在帖子中的第一个 <p> 之前添加一个 template_part(类似于 include())。
我不能在the_content() 之前添加template_part,因为the_content() 内部有时是<figure>,然后是<p>:
<figure>....</figure>
// Want to insert here!
<p>.......</p>
<p>.......</p>
<p>.......</p>
<figure>....</figure>
<p>.......</p>
<p>.......</p>
这是我尝试使用的两个代码,但不知道如何在第一个 <p> 之前使用它:
方法一:
$after = 1;
$content = apply_filters('the_content', $post->post_content);
if(substr_count($content, '<p>') > $after) {
$contents = explode("</p>", $content); $p_count = 0;
foreach($contents as $content){
echo $content; if($p_count == $after){
get_template_part('path/to/part');
} $p_count++;
}
}
方法二:
$paragraphAfter[1] = get_template_part('path/to/part');
$content = apply_filters( 'the_content', get_the_content() );
$content = explode("</p>", $content);
$count = count($content);
for ($i = 0; $i < $count; $i++ ) {
if ( array_key_exists($i, $paragraphAfter) ) {
echo $paragraphAfter[$i];
}
echo $content[$i] . "</p>";
}
最好是更有效的方法,无论是从上面还是你自己的方法:]
【问题讨论】:
标签: php wordpress loops for-loop foreach