2017-05-25 241 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. 
    } 
} 

這是要防止的主題去激活或主題改變你的網站。在這種情況下,您將有一個插件在您的主題中尋找功能,當您更改主題或停用主題時,您的插件將會破壞您的網站。