問題描述

我已經研究了這幾次,但是我的搜索並沒有顯示出很多,除了自定義代碼,這可能是也可能不是很好的 WordPress 實踐。

截至最新版本 (WordPress 3.9 “Smith”),有一個掛鈎添加到插件更新過程中?我問,因為它是一個非常基本的需求,但我沒有看到它添加到 codex(還) 。如果沒有,開發商應採用什麼常見和最佳做法?

編輯:只是為了澄清,我不是在談論激活,而是關於更新,就是説,如果數據庫有變化,否則就可以解決。

最佳解決方案

我不認為已經添加了一個動作。您可以為任何版本 look at version details,並查看添加任何新的操作。

WordPress 的方式來運行插件更新代碼是什麼描述 here

The proper way to handle an upgrade path is to only run an upgrade procedure when you need to. Ideally, you would store a 「version」 in your plugin』s database option, and then a version in the code. If they do not match, you would fire your upgrade procedure, and then set the database option to equal the version in the code. This is how many plugins handle upgrades, and this is how core works as well.

並附有代碼示例 here

function myplugin_update_db_check() {
    global $jal_db_version;
    if (get_site_option( 'jal_db_version' ) != $jal_db_version) {
        jal_install();
    }
}
add_action( 'plugins_loaded', 'myplugin_update_db_check' );

次佳解決方案

來自 discussion where they decided not to add a custom hook/function specific to upgrade,聽起來像”most people”(截至 4 年前) 使用 register_activation_hook,因為當通過管理頁面升級插件時,它被調用; 自那以後,我看到的大多數例子就是這個趨勢。

對於大多數使用情況,我建議不要通過 plugins_loaded 掛起,因為它會在每一頁的加載中被調用。在討論中提到了例外:通過 FTP /SVN 的升級路徑是’edge cases’,因為 WP 不會有機制知道插件已更改,在這種情況下,previous answer 可能更相關。

有關使用 register_activation_hook 的’simple framework’ 示例,請參閲 https://gist.github.com/zaus/c08288c68b7f487193d1

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。