4

I'm having a hard time understanding how to set up a function with a default parameter and then call it with the do_action in WordPress. I'm not sure if this is a WordPress issue or just me not understanding the do_action method. What happens is I define a function like this:

function contact_info( $show_logo=true ) {

    var_dump( $show_logo );    
}

Then I add the hook like this:

add_action( 'show_contact_info', 'contact_info' );

Finally when I call the do_action like this:

do_action('show_contact_info');

I would expect a the var_dump to be bool(true), but what I am getting is: string(0) ""

So my question is WHY?

It doesn't seem to be accepting the default as set in my function, or more specifically, the do_action call ALWAYS seems to pass blank as the first parameter if one is not defined in the call. Is this standard for Wordpress? Why would it not pass NULL?

1
  • In addition to the answer birgire's answer, you can use add_action( 'show_contact_info', 'contact_info', 10, 0 ); to prevent this.
    – swissspidy
    Commented Aug 2, 2017 at 11:33

1 Answer 1

1

When we fire up:

do_action( 'foo' );

we are actually calling:

do_action( 'foo', '' );

That's because how it's defined; With the empty string as the default input argument:

function do_action($tag, $arg = '') {
    // ...
}

So the action's callback get's the empty string as it's first input argument.

This has been like this since at least WordPress version 1.5.

Since WordPress 4.6, do_action() is a wrapper of WP_Hook::do_action();

What if ...

It looks like if it would be defined without the argument part as:

function do_action($tag) {
    // ...
}

and with corresponding modifications to this part:

$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
    $args[] =& $arg[0];
else
    $args[] = $arg;

then we might use the default value, of the first input argument, in our callback.

3
  • 1
    Check out core.trac.wordpress.org/ticket/14881 for some more information on this.
    – swissspidy
    Commented Aug 2, 2017 at 11:31
  • thanks for the trac link @swissspidy Hopefully this will be resolved some day.
    – birgire
    Commented Aug 2, 2017 at 11:35
  • I was just wondering about a possible patch for this, when writing the answer, but it looks like @nacin has already patched it 7 years ago here in #14881.diff ;-)
    – birgire
    Commented Aug 2, 2017 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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