1

I am looking for a way to reproduce what is described in the documentation: An overloaded shortcode callback.

According to the docs, the $atts array will contain the string that matched the shortcode RegEx. The position inside $atts depends on if the callback name matches the shortcode or not. The following example is taken from the docs:

add_shortcode('foo','foo'); // two shortcodes referencing the same callback
add_shortcode('bar','foo');
  produces this behavior:
[foo a='b'] ==> callback to: foo(array('a'=>'b'),NULL,"foo");
[bar a='c'] ==> callback to: foo(array(0 => 'bar', 'a'=>'c'),NULL,"");

So I registered my shortcodes like this:

add_shortcode('foo', 'foo');
add_shortcode('bar', 'foo');
function foo($attributes, $content = null) {
    echo '<pre>';
    var_dump($attributes);
    echo '</pre>';
}

Unfortunately, $attributes is always empty, it does not contain the name of the shortcode (WP 4.0).

Is this an error in the documentation or am I going wrong somewhere?

1

I think you just forgot to run the shortcodes [foo a='b'] and [bar a='c'] through the do_shortcode filter:

do_shortcode( '[foo a='b'] [bar a='c']' )

The output of the_content() is filtered through the do_shortcode, so you can just add it into your editor instead.

Running your code I get the following output for the $arguments dump:

array (size=1)
  'a' => string 'b' (length=1)

and

array (size=1)
  'a' => string 'c' (length=1)

so there's no '0' => 'bar' part here.

But you can get the current shortcode tag from the third parameter of the shortcode callback ( I first heard about it in this answer by @toscho )

I just checked the source and if we check out the do_shortcode_tag function we will find:

// self-closing tag
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null,  $tag ) . $m[6];

where $tag is the third parameter containing the shortcode tag.

So in your case you can change your callback to:

function foo( $attributes = array(), $content = null, $tag = '' ) {

    echo $tag; // current shortcode tag

    echo '<pre>';
    var_dump($attributes);
    echo '</pre>';
}

to get information about the current shortcode tag.

1

Shortcode callbacks get a third argument with the shortcode name. there's a note about this in the docs:

Appears to always appear as third argument as of 2.9.2.

add_shortcode('foo', 'wpse173855_shortcode');
add_shortcode('bar', 'wpse173855_shortcode');

function wpse173855_shortcode($atts, $content, $name)
{
    echo '<pre>';
    var_dump($name);
    echo '</pre>';
}

A look at the source reveals that the shortcode that was matched is always passed in.

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.