Yoan De Macedo [ Web & Minimalism ]

How to detect a WordPress plugin update ?

When you make a WordPress plugin, you probably want to execute code when a user installs a new version of you module.
There is no native process in WordPress to do that (to my knowledge).

You have to build your own system to solve this problem.

First, you have to declare a constant in your code to define the current version.
Here an example :

    class MyPlugin(){

        /* My attributs */

        public function __construct(){
            register_activation_hook( __FILE__, array($this, 'install'));

            /* here other hooks filter ... */

        }

        public function install(){
            /* what to do on install */
        }

        public function method1(){

        }

        public function method2(){

        }

        /* etc ... */
    }

Imagine now I need a table in my database for 1.1 version. I can't use install() method because this method is only called on plugin activation.
If the user replaces the plugin folder without disabling and enabling the plugin again, your code won't be called.

So there is plugins_loaded hook. This hook is called when plugin is loaded. Here, we just have to check version number and to update something if necessary (create a table for example). We have to save the current version into WordPress database to compare it with the current version of the plugin.

    class MyPlugin(){

        const PLUGIN_VERSION = '1.1.0';

        /* my attributs */

        public function __construct(){
            register_activation_hook( __FILE__, array($this, 'install'));
            add_action('plugins_loaded', array($this, 'load_plugin'));  

            /* here other hooks filter ... */

        }

        public function install(){
            /* what to do on install */
        }

        public function load_plugin(){

                if(self::PLUGIN_VERSION != get_option('monplugin_version')){
                    /* Version has changer */
                    /* We make the update process ... */

                    update_option('myplugin_version', self::PLUGIN_VERSION);
                }
        }

        public function method1(){

        }

        public function method2(){

        }
        /* etc ... */
    }

What if a user goes directly from 1.1 to 1.3 ? You have to apply the 1.1 => 1.2 update process and 1.2 => 1.3 update process. So I decided to improve my system to apply multiple patches.

(Post on 2018-06-22)

Blog posts | Who am I ? | mail@yoandm.com

I share information with you.
Signup here. I hate SPAM.
Legal notices | Powered by Grav