Parse Wordpress like Shortcode

前端 未结 6 1766
梦如初夏
梦如初夏 2020-12-15 10:43

I want to parse shortcode like Wordpress with attributes:

Input:

[include file=\"header.html\"]

I need output as array, function na

6条回答
  •  醉酒成梦
    2020-12-15 11:31

    This is actually tougher than it might appear on the surface. Andrew's answer works, but begins to break down if square brackets appear in the source text [like this, for example]. WordPress works by pre-registering a list of valid shortcodes, and only acting on text inside brackets if it matches one of these predefined values. That way it doesn't mangle any regular text that might just happen to have a set of square brackets in it.

    The actual source code of the WordPress shortcode engine is fairly robust, and it doesn't look like it would be all that tough to modify the file to run by itself -- then you could use that in your application to handle the tough work. (If you're interested, take a look at get_shortcode_regex() in that file to see just how hairy the proper solution to this problem can actually get.)

    A very rough implementation of your question using the WP shortcodes.php would look something like:

    // Define the shortcode
    function inlude_shortcode_func($attrs) {
        $data = shortcode_atts(array(
            'file' => 'default'
        ), $attrs);
    
        return "Including File: {$data['file']}";
    }
    add_shortcode('include', 'inlude_shortcode_func');
    
    // And then run your page content through the filter
    echo do_shortcode('This is a document with [include file="header.html"] included!');
    

    Again, not tested at all, but it's not a very hard API to use.

提交回复
热议问题