将每个短码放在数组中放入div

时间:2016-02-01 作者:20yco

我试图用特殊的数据属性将每个短代码包装在div中,但当我使用嵌套的短代码时,它们不会包装,我错在哪里?谢谢

public function wrapShortcode( $content )
{
    preg_match_all( \'/\' . get_shortcode_regex() . \'/\', trim( $content ), $found , PREG_SET_ORDER | PREG_OFFSET_CAPTURE );

    if ( ! empty( $found  ) ) {
        for ( $i = count( $found  ) - 1; $i >= 0; $i-- ) {
            $id = md5( time() . \'-\' . $this->tag_index ++ );
            $match = $found[ $i ];

            $scCont = substr( $content, $match[0][1], strlen( $match[0][0] ) );
            $shortcode = array(
                \'tag\'   => $match[2][0]
            );

            $modifiedShortcode = \'<div class="shortcode" data-name="\'.$shortcode[\'tag\'].\'">\'.$scCont.\'</div>\';
            $content = substr( $content, 0, $match[0][1] ) . $modifiedShortcode . substr( $content, $match[0][1] + strlen( $match[0][0] ) );
        }
    }

    remove_action( \'the_content\', array( $this, \'wrapShortcode\' ), 1 );

    // Stray spaces can create lost paragraph tags.
    $content = preg_replace( \'/(\\/\\w+>)\\s+(<\\/\\w+)/\', \'$1$2\', $content );
    return apply_filters( \'bq_wrapShortcode\', $content );
}
add_filter( \'the_content\', array( $this, \'wrapShortcode\' ), -9999999 );
此代码适用于以下短代码:

[shortcode][/shortcode]
并返回:

<div class="shortcode" data-name="shortcode">[shortcode][/shortcode]</div>
但是,当我使用嵌套的短代码时,我的代码只包装第一个短代码,而不包装内部短代码:

<div class="shortcode" data-name="shortcode">[shortcode][inner_shortcode][/inner_shortcode][/shortcode]</div>
但必须返回:

<div class="shortcode" data-name="shortcode">
     [shortcode]
     <div class="shortcode" data-name="inner_shortcode">
        [inner_shortcode][/inner_shortcode]                 
     </div>
     [/shortcode]
</div>
我错在哪里?谢谢

1 个回复
最合适的回答,由SO网友:bonger 整理而成

您需要递归到短代码内容中($m[5] 返回人get_shortcode_regex()), 使用的标准方式preg_replace_callback():

    public function wrapShortcode( $content )
    {
        $content = preg_replace_callback( \'/\' . get_shortcode_regex() . \'/s\', array( $this, \'wrapShortcodeCallback\' ), $content );

        remove_filter( \'the_content\', array( $this, \'wrapShortcode\' ), -9999999 );

        // Stray spaces can create lost paragraph tags.
        $content = preg_replace( \'/(\\/\\w+>)\\s+(<\\/\\w+)/\', \'$1$2\', $content );
        return apply_filters( \'bq_wrapShortcode\', $content );
    }
    public function wrapShortcodeCallback( $m )
    {
        $id = md5( time() . \'-\' . $this->tag_index ++ );
        if ( $m[5] !== \'\' ) {
            // Recurse into content.
            $m[5] = preg_replace_callback( \'/\' . get_shortcode_regex() . \'/s\', array( $this, \'wrapShortcodeCallback\' ), $m[5] );
            $scCont = \'[\' . $m[1] . $m[2] . $m[3] . \']\' . $m[5] . \'[/\' . $m[2] . \']\' . $m[6];
        } else {
            $scCont = \'[\' . $m[1] . $m[2] . $m[3] . $m[4] . \']\' . $m[6];
        }
        return \'<div class="shortcode" data-name="\'.$m[2].\'">\'.$scCont.\'</div>\';
    }