Nested Shortcode Detection

If you are familiar with this code

<?php
  $pattern = get_shortcode_regex();
  preg_match('/'.$pattern.'/s', $posts[0]->post_content, $matches);
  if (is_array($matches) && $matches[2] == 'YOURSHORTCODE') {
    //shortcode is being used
  }
?>

from this website, but it does not work for nested shortcodes.

Read More

Does anyone know how to make it work for nested shortcodes?

Related posts

Leave a Reply

3 comments

  1. From: http://codex.wordpress.org/Shortcode_API#Limitations

    The shortcode parser correctly deals with nested shortcode macros, provided their handler functions support it by recursively calling do_shortcode()

    It will not let you nest the same shortcode inside another though:

    However the parser will fail if a shortcode macro is used to enclose another macro of the same name

    Assuming you won’t be doing so, here is a contrived example of what you need to do in your shortcode callback:

    function paragraph_wrap($atts, $content) {
    
         // if there are nested shortcodes - handle them
         $content = do_shortcode($content);
    
         // wrap content in a paragraph tag
         $paragraphed = '<p>' . $content . '</p>';
    
         return $paragraphed;
    }
    add_shortcode('wrap_p', 'paragraph_wrap');
    

    Hope this helps.

  2. Just a guess. get_shortcode_regex() only works for registered shortcodes. So just in case you have not registered “your” shortcode it does not even work for simple shortcodes. So this might be – in case you did not register it – the cause of your problem in the end.

    Shortcode handling is specified in the Shortcode API, examples how to register shortcodes are given on the add_shortcode() Codex page as well.

    function baztag_func($atts, $content=) {
        return "content = $content";
    }
    add_shortcode('baztag', 'baztag_func');
    

    For nested codes, Jeff has already answered how this works. So this is basically a smaller example that shows how to add a shortcode. After using add_shortcode(), get_shortcode_regex() will return a regular expression that actually covers the registered shortcode name. Otherwise it just won’t match.

  3. Shortcode matching is implemented in a deficient way (shortcodes.php, ll174). Basically, regular expressions are used to describe what should be a non-regular language (i.e. shortcodes with arbitrary nesting).

    In effect,

    [a]
      [a]
      [/a]
    [/a]
    

    will be parsed so that the opening tag in line 1 matches the closing tag in line 3; obviously, that does not lead to the desired behaviour.