Check for dependent plugin and if false dont activate plugin

I was searching for the same answer this morning for my plugin AnsPress. So I sneak into WordPress plugin wp-admin/includes/plugin.php and got an idea.

WordPress check for fatal error while activating plugin, so simplest solution will be trigger a fatal error and this will prevent WordPress to activate the plugin.

In my below code I check if plugin files exists then get plugin version and if lower dependent version trigger error.

function anspress_activate( $network_wide ) {
    //replace this with your dependent plugin
    $category_ext="categories-for-anspress/categories-for-anspress.php";

    // replace this with your version
    $version_to_check = '1.3.5'; 

    $category_error = false;

    if(file_exists(WP_PLUGIN_DIR."https://wordpress.stackexchange.com/".$category_ext)){
        $category_ext_data = get_plugin_data( WP_PLUGIN_DIR."https://wordpress.stackexchange.com/".$category_ext);
        $category_error = !version_compare ( $category_ext_data['Version'], $version_to_check, '>=') ? true : false;
    }   

    if ( $category_error ) {
        echo '<h3>'.__('Please update all AnsPress extensions before activating. <a target="_blank" href="http://anspress.io/questions/ask/">Ask for help</a>', 'ap').'</h3>';

        //Adding @ before will prevent XDebug output
        @trigger_error(__('Please update all AnsPress extensions before activating.', 'ap'), E_USER_ERROR);
    }
}

register_activation_hook(__FILE__, 'anspress_activate');

This may not be an elegant solution but it works. feel free to update this answer.

Leave a Comment