首页 > 解决方案 > 在 Wordpress 中的 2 个段落之后插入一个 DIV

问题描述

我正在努力让我的帖子在 2 个(或任何数量的)段落之后插入一个拉引号。在我正在使用的网站的情况下,引号是它们自己的字段,所以我不能简单地将它分配给一个块引用标签。因此,我拼凑了这个解决方案:

    function insert_pullquote( $text ) {

    if ( is_singular('review') ) :

        $quote_text = get_template_part( 'pullquote' );
        $split_by = "\n\n";
        $insert_after = 2; //number of paragraphs

        // make array of paragraphs
        $paragraphs = explode( $split_by, $text);

        // if array elements are less than $insert_after set the insert point at the end
        $len = count( $paragraphs );
        if (  $len < $insert_after ) $insert_after = $len;

        // insert $ads_text into the array at the specified point
        array_splice( $paragraphs, $insert_after, 0, $quote_text );

        // loop through array and build string for output
        foreach( $paragraphs as $paragraph ) {
            $new_text .= $paragraph; 
        }

        return $new_text;

    endif;

    return $text;

}
    add_filter('the_content', 'insert_pullquote');

所以,好消息是它显示了我想要的 pullquote(见这里),但在 2 段之后它不会这样做。我正在使用 get_template_part('pullquote'); 的 Wordpress 内置函数,它本身使用 echo(types_render_field('pullquote')); 如果我只输入纯文本,它工作正常。我究竟做错了什么?我有点 PHP 笨拙,所以对于明显的错误请多多包涵。谢谢!

标签: phpwordpressfunction

解决方案


的范围$new_text在循环内。

你需要

    $new_text="";    // declare out side loop
    foreach( $paragraphs as $paragraph ) {
        $new_text .= $paragraph; 
    }
    return $new_text;  // now is available here.

你也可以使用

$new_text =implode($paragraphs);  // to match your explode :-)

推荐阅读