0

When you've got your shortcodes defined like this:

[myform]
    Foo: [mytextbox name="foo"]
[/myform]

And in your php:

function shortcode_myform($atts, $content = null) {
   return '<form action="#" method="post">' . do_shortcode($content) . '</form>';
}
add_shortcode('myform','shortcode_myform');

function shortcode_mytextbox($atts) {
   return '<input type="text" name="'$atts['name']'" />';
}
add_shortcode('mytextbox','shortcode_mytextbox');

What would be the most elegant way to get the name attribute of any children of myform attribute inside the shortcode_myform function?

I figured I could use sessions or globals but that doesn't feel like the right thing to do.

1

Since nobody posted a complete answer, I used the method s_ha_dum described and written a function that returns a shortcode => attributes array/map.

function attribute_map($str, $att = null) {
    $res = array();
    $reg = get_shortcode_regex();
    preg_match_all('~'.$reg.'~',$str, $matches);
    foreach($matches[2] as $key => $name) {
        $parsed = shortcode_parse_atts($matches[3][$key]);
        $parsed = is_array($parsed) ? $parsed : array();

        if(array_key_exists($name, $res)) {
            $arr = array();
            if(is_array($res[$name])) {
                $arr = $res[$name];
            } else {
                $arr[] = $res[$name];
            }

            $arr[] = array_key_exists($att, $parsed) ? $parsed[$att] : $parsed;
            $res[$name] = $arr;

        } else {
            $res[$name][] = array_key_exists($att, $parsed) ? $parsed[$att] : $parsed;
        }
    }

    return $res;
}

Example usage:

Content of the page:

[outer_shortcode]
    [inner_code url="#" title="Hello"]
[/outer_shortcode]

Shortcode implementations:

add_shortcode('outer_shortcode',function($atts,$content) {
    return attribute_map($content);
});

add_shortcode('inner_shortcode',function($atts,$content) {
    return '';
});

This will render to:

Array
(
    [inner_shortcode] => Array
        (
            [url] => #
            [title] => Hello
        )

)
  • Great Joren.Working perfectly.You saved my time.Accepted your answer. Good luck and Thanks a lot!! – Sumith Harshan May 25 '14 at 9:49
  • There might be a small bug in the else statement of the attribute_map function. I noticed that the first element was coming out as a string and not an array. The code is this: } else { $res[$name] = array_key_exists($att, $parsed) ? $parsed[$att] : $parsed; } – Adam Christianson Aug 18 '17 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.