从插件中的主要WordPress主题调用函数

时间:2017-05-25 07:41:28

标签: php wordpress function

我的主题functions.php文件中有一个函数,它返回一个值:

function my_theme_function() {
    return "100";
}

我的主题模板中的任何地方我都可以这样做......

echo my_theme_function()

...我在页面上看到了数字100。那很酷。

但是在我的插件中,我希望能够通过回显my_theme_function()来访问此函数,但是我得到了“调用未定义函数”错误。

最奇怪的部分是我确定这是几天前工作的,但我从那时起就没有触及过代码。我怀疑是一些WordPress恶作剧,但我不知道为什么或如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以获取此结果的原因可以是主题和插件的加载顺序。

例如,您的插件可以在主题之前加载,显然,在这种情况下,它在插件源代码中不可用。

这个问题的解决方案是WordPress Hooks。我不知道你的插件代码样式是什么,但是你可以在init钩子中引导你的插件,或者在after_setup_theme中更好。

例如,让我们说,您需要在WordPress加载主题后运行插件。您可以使用以下代码执行此操作:

function my_theme_is_loaded() {
    // Bootstrap your plugin here
    // OR
    // try to run your function this way:

    if ( function_exists( 'my_theme_function' ) ) {
        my_theme_function();
    }
}
// You can also try replace the `after_setup_theme` with the
// `init`. I guess it could work in both ways, but whilw your
// plugin rely on the theme code, the following is best option.
add_action( 'after_setup_theme', 'my_theme_is_loaded' );

上面代码的作用,就像你对你的插件说的那样,等到主题完全加载,然后尝试运行依赖于主题代码的插件代码。

当然,我建议将主题函数包装在一个插件函数中:

// This way, your plugin will continue running even if you remove
// your theme, or by mistake your rename the function in the theme
// or even if you totally decide to remove the function at all in the
// side of the theme.
function function_from_theme() {
    if ( function_exists( 'my_theme_function' ) ) {
        return my_theme_function();
    } else {
        return 0; // Or a value that is suitable with what you need in your plugin.
    }
}

这将保护您的网站免受主题取消激活或主题更改。在这种情况下,您将有一个插件在您的主题中寻找功能,当您更改主题或停用主题时,您的插件将破坏您的网站。