[英]Call function from main WordPress theme in a plugin
我的主題functions.php文件中有一個函數,該函數返回一個值:
function my_theme_function() {
return "100";
}
在主題模板的任何地方,我都可以簡單地執行此操作...
echo my_theme_function()
...我在頁面上看到數字100。 這很酷。
但是在我的插件中,我希望能夠通過回顯my_theme_function()來訪問該函數,但是卻收到“未定義函數的調用”錯誤。
最奇怪的部分是我確定這是在幾天前起作用的,但是從那以后我再也沒有碰過代碼。 我懷疑有些WordPress惡作劇,但我不知道為什么或如何解決這個問題。
您可能會得到此結果的原因可能是主題和插件的加載順序。
例如,您的插件可以在主題之前加載,顯然,在這種情況下,插件的源代碼中不提供該功能。
解決此問題的方法是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.
}
}
這將保護您的網站免受主題停用或主題更改的影響。 在這種情況下,您將需要一個插件來尋找主題中的功能,並且在更改主題或停用主題時,該插件會破壞您的網站。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.