Last active
February 21, 2024 21:32
-
-
Save igorbenic/9027f18f25525fc76ebbbf3988396706 to your computer and use it in GitHub Desktop.
Upgrade Process Example in WordPress
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 | |
/** | |
* This class can be used as an installer class to install tables and such. | |
* And it can be also used to make updates. | |
*/ | |
class My_Plugin_Installer() { | |
/** | |
* Update functions for versions. | |
* Have this functions defined elsewhere. | |
*/ | |
public $updates = array( | |
'1.1.0' => 'my_plugin_update_110', | |
'1.2.0' => 'my_plugin_update_120', | |
); | |
/** | |
* Check from which version we are updating. | |
* | |
* @param string $from_version This version is retrieved from the option. It's still the old version because we are updating the option after the updates. | |
* | |
* @return void | |
*/ | |
public function update( $from_version ) { | |
if ( ! defined( 'MY_PLUGIN_UPDATING' ) ) { | |
define( 'MY_PLUGIN_UPDATING', true ); | |
} | |
foreach ( $this->updates as $version => $update_function ) { | |
if ( version_compare( $from_version, $version, '<' ) ) { | |
$update_function(); | |
} | |
} | |
update_option( 'giveasap_version', MY_PLUGIN_VERSION ); | |
} | |
} | |
// Defined elsewhere. | |
function my_plugin_update_110() {} | |
function my_plugin_update_120() {} |
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 | |
/** | |
* This is your main plugin class (or file). | |
* Or at least a file that's included when plugin is called. | |
*/ | |
define( 'MY_PLUGIN_VERSION', '1.2.0' ); | |
add_action( 'init', 'my_plugin_check_versions' ); | |
/** | |
* This function will be called to check for a new plugin version. | |
* If this is the first time we run this, the get_option will return 1.0.0 because it's the default value. | |
*/ | |
function my_plugin_check_versions() { | |
if ( ! defined( 'IFRAME_REQUEST' ) && get_option( 'my_plugin_version', '1.0.0' ) !== MY_PLUGIN_VERSION ) { | |
$installer = new My_Plugin_Installer(); | |
$installer->update( get_option( 'my_plugin_version', '1.0.0' ) ); | |
do_action( 'my_plugin_updated', MY_PLUGIN_VERSION ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment