問題描述

我有一切準備發佈我的插件的新版本,但最後一個問題是…

舊版本沒有關鍵選項名稱的命名約定。

選項增長,我更名為所有,使用前綴為了良好的編碼實踐和我自己的理智。

我想在説明和更改日誌中發出警告,但我認為如果我可以進行內部導入方法,那將會變得更加温和。

那就是這個問題:

  • 如何運行插件更新功能?

  • 如何檢查 $ myOptions [‘old_key’] 是否存在,將其傳遞給 $ myOptions [‘new_key’],最後刪除 old_key

謝謝,

最佳解決方案

你應該在數據庫中存儲你的插件的版本號 (如果你還沒有,添加這個 pronto),使用它可以這樣做 (注意這是偽代碼):

if( $db_version < {your desired version} ) {
    // previous updates and such
    $db_version = $new_version; //put that in the database
}
if( $db_version < $current_version ) {
    create $options array
    foreach( $option as $o ) {
        if( get_option( $o['old_name'] ) ) {
            update_option( $o['new_name'], get_option( $o['old_name'] ) );
            delete_option( $o['old_name'] ); //clean up behind yourself
        }
    }
    and then update your database version again
}

然後,當您發佈下一次更新時,將 $current_version 更改為發生更改的版本。使用這種方法的原因是,如果你的更新是永遠的 (也就是説,你不能從 1.1 到 1.9,你必須打到 1.3 和 1.5 之間或類似的東西),你將有一個結構到位來管理。如果它變得複雜,我會經常保持代碼乾淨,只需要 if 語句執行類似 wpse49717_plugin_release_150(),並管理更新等。

我只想注意 (真的,重申),你應該只使用這個結構來進行不必要的更新。您應該完全期望此代碼只能運行 ONCE,因此請確保您正在更新數據庫版本等。

次佳解決方案

這是一個更好,更自動化的方法 (以下 this 答案):

class MyPlugin{

  const
    OPTION_NAME = 'my_plugin_options',
    VERSION     = '1.0';

  protected
    $options  = null,

    // default options and values go here
    $defaults = array(
                  'version'     => self::VERSION, // this one should not change
                  'test_option' => 'abc',
                  'another_one' => 420,
                );

  public function getOptions(){

    // already did the checks
    if(isset($this->options))
      return $this->options;

    // first call, get the options
    $options = get_option(self::OPTION_NAME);

    // options exist
    if($options !== false){

      $new_version = version_compare($options['version'], self::VERSION, '!=');
      $desync = array_diff_key($this->defaults, $options) !== array_diff_key($options, $this->defaults);

      // update options if version changed, or we have missing/extra (out of sync) option entries
      if($new_version || $desync){

        $new_options = array();

        // check for new options and set defaults if necessary
        foreach($this->defaults as $option => $value)
          $new_options[$option] = isset($options[$option]) ? $options[$option] : $value;

        // update version info
        $new_options['version'] = self::VERSION;

        update_option(self::OPTION_NAME, $new_options);
        $this->options = $new_options;

      // no update was required
      }else{
        $this->options = $options;
      }


    // new install (plugin was just activated)
    }else{
      update_option(self::OPTION_NAME, $this->defaults);
      $this->options = $this->defaults;
    }

    return $this->options;

  }

}

首先致電 $this->getOptions()將對您的選項進行所有必要的更新。你需要調整的唯一的事情是常量/$ defaults 變量。

參考文獻

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