5 An API for creating shortcode tags that support attributes and enclosed content, such as:
8 [shortcode foo="bar" baz="bing" /]
9 [shortcode foo="bar"]content[/shortcode]
11 tag and attrbute parsing regexp code based on the Textpattern tag parser.
13 To apply shortcode tags to content:
15 $out = do_shortcode($content);
17 Simplest example of a shortcode tag using the API:
20 function footag_func($atts) {
21 return "foo = {$atts[foo]}";
23 add_shortcode('footag', 'footag_func');
25 Example with nice attribute defaults:
28 function bartag_func($atts) {
29 extract(shortcode_atts(array(
31 'baz' => 'default baz',
34 return "foo = {$foo}";
36 add_shortcode('bartag', 'bartag_func');
38 Example with enclosed content:
40 // [baztag]content[/baztag]
41 function baztag_func($atts, $content='') {
42 return "content = $content";
44 add_shortcode('baztag', 'baztag_func');
48 $shortcode_tags = array();
50 function add_shortcode($tag, $func) {
51 global $shortcode_tags;
53 if ( is_callable($func) )
54 $shortcode_tags[$tag] = $func;
57 function remove_shortcode($tag) {
58 global $shortcode_tags;
60 unset($shortcode_tags[$tag]);
63 function remove_all_shortcodes() {
64 global $shortcode_tags;
66 $shortcode_tags = array();
69 function do_shortcode($content) {
70 global $shortcode_tags;
72 if (empty($shortcode_tags) || !is_array($shortcode_tags))
75 $pattern = get_shortcode_regex();
76 return preg_replace_callback('/'.$pattern.'/s', 'do_shortcode_tag', $content);
79 function get_shortcode_regex() {
80 global $shortcode_tags;
81 $tagnames = array_keys($shortcode_tags);
82 $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
84 return '\[('.$tagregexp.')\b(.*?)(?:(\/))?\](?:(.+?)\[\/\1\])?';
87 function do_shortcode_tag($m) {
88 global $shortcode_tags;
91 $attr = shortcode_parse_atts($m[2]);
94 // enclosing tag - extra parameter
95 return call_user_func($shortcode_tags[$tag], $attr, $m[4]);
98 return call_user_func($shortcode_tags[$tag], $attr);
102 function shortcode_parse_atts($text) {
104 $pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
105 $text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
106 if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) ) {
107 foreach ($match as $m) {
109 $atts[strtolower($m[1])] = stripcslashes($m[2]);
110 elseif (!empty($m[3]))
111 $atts[strtolower($m[3])] = stripcslashes($m[4]);
112 elseif (!empty($m[5]))
113 $atts[strtolower($m[5])] = stripcslashes($m[6]);
114 elseif (isset($m[7]) and strlen($m[7]))
115 $atts[] = stripcslashes($m[7]);
116 elseif (isset($m[8]))
117 $atts[] = stripcslashes($m[8]);
120 $atts = ltrim($text);
125 function shortcode_atts($pairs, $atts) {
126 $atts = (array)$atts;
128 foreach($pairs as $name => $default) {
129 if ( array_key_exists($name, $atts) )
130 $out[$name] = $atts[$name];
132 $out[$name] = $default;
137 add_filter('the_content', 'do_shortcode', 11); // AFTER wpautop()