0

I'm curious how to process shortcodes in arguments (not nested shortcodes, which are already contemplated)::

function do_foo_shortcode($atts, $content = null) {
    extract(shortcode_atts(array(
        'bar' => '',
    ), $atts, 'foo'));

    $bar = do_shortcode($bar);
    $content = do_shortcode($content);

    return "$bar - $content";
}
add_shortcode('foo', 'do_foo_shortcode');

For example in:

[foo bar=[video src="video-source.mp4"]]Hello world![/foo]

generates:

[video - ]Hello world!

How can I consider such cases and how to correctly use them?

  • Honestly I think this is just a severe misuse of shortcodes. I’d suggest finding an alternative approach. At the very least you could just support a src argument on your own shortcode and then just pass that to the underlying function of the video shortcode, rather than trying to mash them together like this. – Jacob Peattie Sep 19 '18 at 15:20
  • @JacobPeattie I understand your point and I really appreciate it (I'm quite new with WP). The complete scenario is that we have several shortcodes (with several options each one) that already generate the desired code, but now we want to use them to feed more complex blocks, so creating special cases for each combination seemed inappropriate, so I thought about reusing them as parameters (more like regular functions). – cbuchart Sep 19 '18 at 15:26
  • You've even used the term "blocks." It might be a good time to test out Gutenberg and see whether some of its built-in blocks, or even custom blocks, would work better in a more WP way. – WebElaine Sep 19 '18 at 15:31
  • You can't nest shortcodes inside attributes like that, the shortcode parser doesn't work that way – Tom J Nowell Sep 19 '18 at 16:09
  • 2
    Also avoid extract( calls like the plague – Tom J Nowell Sep 19 '18 at 16:10
0

A partial solution I've found so far is to escape the brackets in the initial call, then replace the escaped characters in the do_foo_shortcode function.

function do_foo_shortcode($atts, $content = null) {
    extract(shortcode_atts(array(
        'bar' => '',
    ), $atts, 'foo'));

    $bar = str_replace("[", "[", $bar);
    $bar = str_replace("]", "]", $bar);
    $bar = do_shortcode($bar);
    $content = do_shortcode($content);

    return "$bar - $content";
}

And calling it as

[foo bar="[video src=video-source.mp4]"]Hello world![/foo]

Of course, this is an incomplete solution since it doesn't allow more than 1-level nesting, and quote marks cannot be used in the inner shortcode. Not to mention how complicate is to write it.

| improve this answer | |

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.