8

I am having trouble wrapping my head around these two functions. I understand do_action() but I don't see clearly when do_action_ref_array() would be useful. Couldn't we pass an array to do_action() as well?

1 Answer 1

19
  • If you pass an array to do_action_ref_array(), each element’s value of that array will be passed as a separate parameter to the callback. The keys are lost.

  • If you pass an array to do_action(), the complete array will be passed as one single parameter to the callback. The keys stay intact.

Let’s look at the differences between do_action() and do_action_ref_array() in a simple plugin:

add_action( 'wp_footer',             'action_diff_test' );
add_action( 'diff_action',           'diff_test_callback', 10, 999 );
add_action( 'diff_action_ref_array', 'diff_test_callback', 10, 999 );

/**
 * call test actions
 */
function action_diff_test()
{
    $args = array (
        'foo'   => 'bar',
        'hello' => 'world',
        0       => 123
    );

    do_action(           'diff_action',           $args );
    do_action_ref_array( 'diff_action_ref_array', $args );
}
/**
 * callback for test actions
 */
function diff_test_callback()
{
    $args = func_get_args();
    print current_filter() . ', ' . func_num_args() . ' arguments';
    ?>
    <pre><?php
    print htmlspecialchars(
        print_r( $args, TRUE ),
        ENT_QUOTES,
        'utf-8',
        FALSE
    );
    ?></pre>
    <?php
}

Result:

diff_action, 1 arguments 
Array
(
    [0] => Array
        (
            [foo] => bar
            [hello] => world
            [0] => 123
        )

)

diff_action_ref_array, 3 arguments 
Array
(
    [0] => bar
    [1] => world
    [2] => 123
)

do_action_ref_array() was introduced 2006 to handle parameters passed by reference better in PHP 4. A review of the function 2011 was closed as wontfix. But the conclusion was not to use for new functions in WordPress anymore, because in PHP 5 you can do that with do_action() too. The problem from 2006 is not a problem nowadays.

Do not use do_action_ref_array() in your custom hooks, but learn how to read it.

3
  • Hi fuxia! I'm not understanding why you used 999 as the number of arguments. I was expecting that to be add_action('a', 'c', 999, 1); and add_action('b', 'c', 999, 3);
    – brasofilo
    Commented Jul 12, 2021 at 23:51
  • @brasofilo That's because you don't always know how big the incoming array is.
    – fuxia
    Commented Jul 12, 2021 at 23:54
  • I see now, makes perfect sense. Thanks for the feedback
    – brasofilo
    Commented Jul 13, 2021 at 0:10

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.