2017-05-25 242 views
0

我在主题的functions.php文件中的函数返回一个值:呼叫功能

function my_theme_function() { 
    return "100"; 
} 

港九我的主题模板,我可以简单地做到这一点...

echo my_theme_function() 

...我看到页面上的数字100。这很酷。

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

最奇怪的部分是我确定这是几天前的工作,但我从未触及代码。我怀疑一些WordPress shenanigans,但我不知道为什么或如何解决这个问题。

+0

如果我的答案解决了您的问题,请随时加快速度,并用勾号标记答案。谢谢 ;) :) –

回答

0

您可能会采用此结果的原因可能是主题和插件的加载顺序。

例如,您的插件可以在主题之前加载,显然,在这种情况下,您的插件源代码中无法使用该功能。

这个问题的解决方案是WordPress的钩子。我不知道你的插件代码风格是什么,但你可以引导你的插件在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. 
    } 
} 

这是要防止的主题去激活或主题改变你的网站。在这种情况下,您将有一个插件在您的主题中寻找功能,当您更改主题或停用主题时,您的插件将会破坏您的网站。