Last active
December 12, 2015 07:48
-
-
Save aaroneaton/4739430 to your computer and use it in GitHub Desktop.
WP:Plugin option upgrade
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment