【问题标题】:Inserting content before <p> tags in PHP在 PHP 中的 <p> 标记之前插入内容
【发布时间】:2013-04-23 22:03:17
【问题描述】:

虽然这是面向 Wordpress 的,但我认为 PHP 的基础更多的是 Stackoverflow 问题:

我想在帖子中的第一个 &lt;p&gt; 之前添加一个 template_part(类似于 include())。

我不能在the_content() 之前添加template_part,因为the_content() 内部有时是&lt;figure&gt;,然后是&lt;p&gt;

<figure>....</figure>
// Want to insert here!
<p>.......</p>
<p>.......</p>
<p>.......</p>
<figure>....</figure>
<p>.......</p>
<p>.......</p>

这是我尝试使用的两个代码,但不知道如何在第一个 &lt;p&gt; 之前使用它:

方法一:

$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


    【解决方案1】:

    一个肮脏的黑客可能是:

    function add_the_string_filter( $content ) {
      $string_to_append = 'your string to add';
      $content = preg_replace('/<p>/',  $string_to_append . '<p>', $content , 1);
    
      return $content;
    }
    
    add_filter( 'the_content', 'add_the_string_filter' );
    

    preg_replace 的最后一个参数是限制,表示只替换第一次出现的地方。

    【讨论】:

    • 所以这行得通,但我很好奇为什么它是一个“肮脏的黑客”而不是普通代码?
    • 我不确定,也许有一些 WordPress 大师会做的更好的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多