0

I wrote a function in my theme's functions.php and am attempting to register it with add_shortcode() as shown in the Codex:

<?php
/**
 * theme's functions.php
 */

namespace MyNamespace;

//[foobar]
function foobar_func( $atts ){
    return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

However this does not work and a post containing [foobar] simply renders "[foobar]" as text instead of being replaced by the handler function's return value.

My guess is it has something to do with my functions.php being namespaced. Does something special need to be done to reference namespaced Callables in add_shortcode?

1 Answer 1

1

Thanks to Stanislav Khromov (also active on WPSE!), I learned any Callable referenced in add_shortcode() must be fully qualified, even if it is defined in the same file you're referencing it.

<?php
/**
 * theme's functions.php
 */

namespace MyNamespace;

//[foobar]
function foobar_func( $atts ){
    return "foo and bar";
}
add_shortcode( 'foobar', '\MyNamespace\foobar_func' );

You may omit the leading backslash, if you prefer: add_shortcode( 'foobar', 'MyNamespace\foobar_func' );

1
  • 1
    You can make it dynamic if in the future the namespace will change you will not have to manually edit the add_shortcode function, using __NAMESPACE__ magic constant. Commented Nov 8, 2021 at 7:43

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.