Check For WordPress Plugin Updates

If you write and contribute plugins to the WordPress Repository then you might be interested in having your plugin be aware of updates you have made available – an admin notice or something similar. Maybe design a clever versioning scheme so that you can inform the user of critical fixes in a more dramatic way than regular patches.

Check For WordPress Plugin Updates

// Your plugin file, perhaps __FILE__?
$plugin_file = 'plugin-name/plugin-file.php';

// Check for Plugin updates, if you want to have the latest (not necessarily recommended)
wp_update_plugins();

// Results of the update check
$update_plugins = get_site_transient( 'update_plugins' );
if ( isset( $update_plugins->response[ $plugin_file ] ) ) {
    // Your plugin needs an update, do something about it?
}

Plugins With Updates

In the result of update_plugins the $update_plugins->response is an array() that will be something like the following, if there is anything else you want to check.

'response' => 
  array (
    'plugin-dir/plugin-file.php' => 
    stdClass::__set_state(array(
       'id' => '12345',
       'slug' => 'plugin-slug',
       'plugin' => 'plugin-name/plugin-file.php',
       'new_version' => '1.2.3',
       'url' => 'https://wordpress.org/plugins/plugin-name/',
       'package' => 'https://downloads.wordpress.org/plugin/plugin-name.1.2.3.zip',
    )),
),

Compare Installed and Available WordPress Plugin Versions

function my_admin_notice() {
    global $my_admin_notice;
    ?>
    <div class="updated">
        <p><?php _e( 'An update is available for your plugin!', 'my-text-domain' ); ?>
        <?php echo $my_admin_notice; ?></p>
    </div>
    <?php
}

function check_update_notices(){
    global $my_admin_notice;
    $plugin_file = 'plugin-name/plugin-file.php';
    $installed_ver = split( ',', $update_plugins->checked[$plugin_file] );
    $available_ver = split( ',', $update_plugins->response[$plugin_file]->new_version );
    $v1 = $installed_ver[0];
    $v2 = $available_ver[0];
    if ( $v1 != $v2 ){
        $behind = $v2-$v1;
        $my_admin_notice = $behind!=1? "Oh no, you're {$behind} major version(s) behind!" : "";
        add_action( 'admin_notices', 'my_admin_notice' );
        return;
    }
}

You may also like...

Leave a Reply

Your email address will not be published.