Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
1  
My solution to this question should be what you need. –  s_ha_dum Nov 7 '13 at 14:23
    
@s_ha_dum That's actually kind of smooth. Thanks! –  Joren Nov 7 '13 at 14:27
add comment

1 Answer

up vote 0 down vote accepted

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
        )

)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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