dongtong1226 2019-08-09 07:20
浏览 56

如何在wordpress中递归解码短代码

I am trying to call shortcodes recursively. The idea is to use shortcodes within a shortcode, I tried exploding the string tried some other logics but none worked.

Can you please help.

I'll share an example below.

add_shortcode( 'first', function ( $attr ) {
    return 'First ' . $attr['key1'] . ' ' . $attr['key2'];
} );
add_shortcode( 'second', function ( $attr ) {
    return 'Second ' . $attr['key1'] . ' ' . $attr['key2'];
} );
add_shortcode( 'third', function ( $attr ) {
    return 'Third ' . $attr['key1'];
} );

Now suppose the string is $string = '[first key1="[second key1="abcd" key2="shortcode"]" key2="[third key1="shortcode"]"]';

OR $string = '[first key1="[second key1="abcd" key2="[third key1="shortcode"]"]" key2="[third key1="shortcode"]"]';

Now most probably the output for first string should be something like this: 'First Second abcd shortcode Third shortcode'

And for the second one should be something like this: 'First Second abcd Third shortcode Third shortcode'

But I am not getting the result. Can someone help me to create a function which takes a string and recursively checks for the shortcode and then execute them (do_shortcode).

  • 写回答

1条回答 默认 最新

  • dongzhi5587 2019-08-09 12:31
    关注

    Finally figured out on my own how to achieve this.

    Took some break and after that the solution just came into my mind.

    I am adding the code below for people who might face the same issue in future.

        public function maybe_parse_nested_merge_tags( $string ) {
            $position_end = strpos( $string, ']' );
            if ( false === $position_end ) {
                return $string;
            }
    
            $split          = str_split( $string, $position_end );
            $position_start = strrpos( $split[0], '[', - 1 );
    
            if ( false === $position_start ) {
                return $string;
            }
    
            $shortcode_array = explode( '[', $split[0] );
            $shortcode       = end( $shortcode_array );
            $result          = do_shortcode( '[' . $shortcode . ']' );
    
            $string = str_replace( '[' . $shortcode . ']', $result, $string );
    
            return $this->maybe_parse_nested_merge_tags( $string );
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多