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

Php 从插件中的主WordPress主题调用函数,php,wordpress,function,Php,Wordpress,Function,我的theme functions.php文件中有一个函数,它返回一个值: function my_theme_function() { return "100"; } 在我的主题模板的任何地方,我都可以简单地做到这一点 echo my_theme_function() …我在页面上看到了数字100。那很酷 但是在我的插件中,我希望通过回显我的函数()也能访问这个函数,但是我得到了一个“调用未定义函数”错误 最奇怪的是,我确信这在几天前是有效的,但从那以后我就再也没有接触过代码。我怀

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

function my_theme_function() {
    return "100";
}
在我的主题模板的任何地方,我都可以简单地做到这一点

echo my_theme_function()
…我在页面上看到了数字100。那很酷

但是在我的插件中,我希望通过回显我的函数()也能访问这个函数,但是我得到了一个“调用未定义函数”错误


最奇怪的是,我确信这在几天前是有效的,但从那以后我就再也没有接触过代码。我怀疑WordPress会有一些恶作剧,但我不知道为什么或者如何避开它。

你之所以会得到这个结果,可能是因为主题和插件的加载顺序

例如,您的插件可以在主题之前加载,显然,在本例中,插件源代码中没有它的功能

这个问题的解决方案是WordPress挂钩。我不知道你的插件代码风格是什么,但是你可以在
init
hook中引导你的插件,或者在
after\u setup\u主题中引导你的插件

比如说,你需要你的插件在主题被
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.
    }
}

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

如果我的答案解决了你的问题,请随意评分,并在答案上打勾。谢谢;):)