WordPress provides many hooks and filters which can be used to customize the site one such function is register_activation_hook() which gets executed when we activate the plugin. When we activate the plugin we can perform many tasks such as checking if the plugin we are activating is compatible with the WordPress version installed, Setting up our plugin and so on. In this tutorial, I’m going to talk on how to use this function to check compatibility of the WordPress version installed with the plugin.

Before taking a look at how can we achieve that let’s first see the usage of the register_activation_hook() function:

<?php 

register_activation_hook( $file, $function ); 

?>

Parameters:

  • $file – Path of the main plugin file goes here.
  • $function – The function name to be executed

Now, let’s jump into the example:

<?php

function check_version_compatibility () {
    global $wp_version;
    
    if( version_compare( $wp_version, "4.0", "<" ) ) {
        deactivate_plugins( basename( __FILE__ ) );
        wp_die( 'Plugin requires version 4.0 or higher' );
    }
}

register_activation_hook( __FILE__, 'check_version_compatibility ' );

?>

In the above code snippet first we’ve created the function check_version_compatibility() in which we have a $wp_version WordPress global variable which stores the current WordPress version installed. Then, We are checking whether the current WordPress version installed is less than the version 4.0 and if it is true then it deactivates the plugin and outputs “Plugin requires version 4.0 or higher“.

In the register_activation_hook() function the first parameter we have passed is __FILE__ which is a PHP’s magic constant and returns the location of the file from which it is called and the second parameter is the function name which we want to execute.

Leave a Reply

Your email address will not be published. Required fields are marked *