1

I wanted to set a default value for a parameter:

function my_function( $arg = 'foo' ) {
    echo $arg
}
add_action('my_action', 'my_function');

function my_2nd_function( $arg = 'bar' ) {
    echo $arg
}
add_action('my_action', 'my_2nd_function');

But when I call them doing the action

do_action('my_action');

I realized that it didn't print anything. I know I can set up the number of arguments a function can receive

add_action('my_action', 'my_function', 10, 1);

And pass it when doing the action

do_action('my_action', 'foo');

But, what should I do when there are multiple functions hooked on that action? Recommendations?

1 Answer 1

2

The value for the default output should be passed to do_action() as the second parameter. E.g.:

do_action( 'my_action', '<p>Default output</p>' );

Note that the above code will not actually output anything. It's just going to fire the callbacks attached to the my_action hook and it will pass '<p>Default output</p>' to those functions.

You can modify the output using callbacks attached to the my_action hook:

add_action( 'my_action', 'my_function', 10, 1 );
function my_function( $default_output ) {
    echo '<p>foo</p>';
}

add_action( 'my_action', 'my_2nd_function', 10, 1 );
function my_2nd_function( $default_output ) {
    echo '<p>bar</p>';
}

add_action( 'my_action', 'my_3rd_function', 10, 1 );
function my_3rd_function( $default_output ) {
    echo $default_output;
}

Output:

<p>foo</p>
<p>bar</p>
<p>Default output</p>

Using a filter might make more sense here. E.g.:

echo apply_filters( 'my_filter', '<p>Default output</p>' );

The output will be determined by the last filter fired on the my_filter hook:

add_action( 'my_filter', 'my_filter_function_1', 10, 1 );
function my_filter_function_1( $default_output ) {
    return $default_output;
}

add_action( 'my_filter', 'my_filter_function_2', 20, 1 );
function my_filter_function_2( $default_output ) {
    return '<p>my_filter_function_2() output</p>';
}

add_action( 'my_filter', 'my_filter_function_3', 30, 1 );
function my_filter_function_3( $default_output ) {
    return '<p>my_filter_function_3() output</p>';
}

Output:

<p>my_filter_function_3() output</p>

If no callbacks are attached to my_filter, the output would be:

<p>Default filter output</p>

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.