• Resolved Imagewpshushu

    (@wpshushu)


    Hi,

    I defined a function foo inside wp-content/themes/mytheme/functions.php, say it looks like this:

    function foo($msg = ”) { … error_log( $msg ); …. }

    Then I created a snippet to call it, ended up with a undefined function error.

    In the mean time, I have a custom class defined in functions.php too:

    MyClass { public static MYCONSTANT = ….. }

    The snippent can access MyClass::MYCONSTANT with no problem.

    Why?

    Thanks

    • This topic was modified 1 year, 5 months ago by Imagewpshushu.
    • This topic was modified 1 year, 5 months ago by Imagewpshushu.
Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Author ImageShea Bunge

    (@bungeshea)

    Hi @wpshushu,

    I suspect that this might be due to load order – snippets are loaded *before* theme files, so functions defined in theme files won’t be available immediately when snippets are loaded.

    Have you tried calling the function inside a later action hook, e.g.:

    add_action( 'after_setup_theme', function () {
    foo( 'bar' );
    } );
    Thread Starter Imagewpshushu

    (@wpshushu)

    @bungeshea Snippet can access MyClass::MYCONSTANT which is also defined in functions.php, though.

    Thread Starter Imagewpshushu

    (@wpshushu)

    @bungeshea My mistake, snippets can access MyClass::MYCONSTANT is because it was called in a HOOK.

    Thread Starter Imagewpshushu

    (@wpshushu)

    @bungeshea What’s the best place to put the definition of a custom function so it’s immediately callable by any code snippet, I mean not in any HOOK but as top level statements in the snippet?

    Plugin Author ImageShea Bunge

    (@bungeshea)

    You should be able to add it as a snippet and set it to have a low number for its priority value.

    Otherwise, including it in a plugin or must-use plugin should mean it’s available for snippets to use when they are loaded.

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘function defined in functions.php not callable from snippet code’ is closed to new replies.