代码之家  ›  专栏  ›  技术社区  ›  Mark Tjan

在Wordpress中的两段后插入DIV

  •  0
  • Mark Tjan  · 技术社区  · 6 年前

    我试着让我的帖子在2段(或任意数量的)后插入一个pullquote。在我使用的网站中,引号是它们自己的字段,所以我不能简单地将其分配给blockquote标记。因此,我拼凑出了这个解决方案:

        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( see here ),但在这两段之后就没有了。我使用的是Wordpress'get_template_part('pullquote');的内置函数,它本身使用echo(types_render_field('pullquote'))从字段中提取;如果我只输入纯文本,就可以了。我做错什么了?我是一个有点PHP乱七八糟,所以请容忍我的明显错误。谢谢!

    1 回复  |  直到 6 年前
        1
  •  0
  •   bcperth    6 年前

    范围 $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 :-)