I want to use namespaces instead of prefixes for a plugin, since now the minimum supported PHP version for WP is 5.6.20 and namespaces can be used.

But it does not seem to work with hooks:

namespace My\Whatever;

// Enqueue CSS and JS
function enqueue_css_and_js() {
    // Do it...
add_action( 'wp_enqueue_scripts', 'enqueue_css_and_js' );

Results in this error:

call_user_func_array() expects parameter 1 to be a valid callback, function 'enqueue_css_and_js' not found or invalid function name

However, if I prefix the function with the namespace:

add_action( 'wp_enqueue_scripts', 'My\Whatever\enqueue_css_and_js' );

It works as expected.

I wonder why this happens, since I am writing this inside the same PHP file.

And the real question is:

Should I always prefix all my functions with the namespace when referencing callbacks in WordPress, or does this only happen in certain cases with certain hooks?

By referencing callbacks, I mean all of them, not only for actions and filters, but also for the callbacks in add_settings_section(), add_meta_box(), etc...

  • 3
    If use use namespaces then yes, you will always have to prefix it. PHP has a magic constant __NAMESPACE__ you can use instead of manualy typing the prefix each time, that way if you would ever need to change the namespace, everything will keep working as expected because you used the __NAMESPACE__ magic constant Aug 10 '21 at 9:15
  • 1
    "I wonder why this happens, since I am writing this inside the same PHP file" - this doesn't really matter here. You do add the action within your file, but the code that triggers this action/callback is somewhere in Core WP. Meaning: the execution part is not in the same namespace/file, hence you need to add it.
    – kero
    Aug 10 '21 at 9:32
  • @kero Thank you for the explanation :) Aug 10 '21 at 9:34
  • @Buttered_Toast Thanks for the tip! :) Aug 10 '21 at 9:34
  • 2
    Also note that callbacks are a PHP feature, not a WordPress feature. So this behaviour has nothing to do with WordPress. See: php.net/manual/en/language.types.callable.php#119166 Aug 10 '21 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.