I'm working on a plugin that needs to create a CSV file upon it's activation. I want to notice the user if for some reason the file couldn't be open, and prevent the plugin's activation. Here's my code so far:

public static function hcg_create_csv_file(){
    try {
        $file_name = self::FILE_NAME;
        $fields    = self::get_csv_head_fields();

        $file = fopen( HCG_ABSPATH . 'src/' . $file_name, 'w' );
        if ( ! $file ) {
            throw new Exception(__('Failed to open CSV file, please check your directory permissions.', ''));

        fputcsv( $file, $fields );
        fclose( $file );

    } catch (Exception $e) {
        $GLOBAL['hcg_activation_error_msg'] = $e->getMessage();
        deactivate_plugins( basename( __FILE__ ) );
        $redirect_url = add_query_arg('hcg_activation_error_msg', 1, admin_url('plugins.php'));

And the activation hook ("Hashavshevet_CSV_Generator" is the name of the main plugin class"):

register_activation_hook( HCG_PLUGIN_FILE, array('Hashavshevet_CSV_Generator', 'hcg_create_csv_file') );

As you can see what I've tried to do in this function in case of an error is to refresh the page with a new url parameter which will indicate there is an error, also I put the error message in a global variable so I will be able to access it from the admin_notices() function, here's the fuction hooked to admin_notices():

function hcg_add_admin_error_msg(){
    if ( isset($_GET['hcg_activation_error_msg']) ) {
        global $hcg_activation_error_msg;
        $class   = 'notice notice-error';

        printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $hcg_activation_error_msg ) );
add_action('admin_notices', 'hcg_add_admin_error_msg');

The problem is because the plugin is not activate, this function don't run, as it located (and should be located) in the plugin file.

Any idea how to go around this?

Thanks in advance!!

  • please do not bump questions. this questions was answered before, and as you say yourself it is impossible, end of story. – Mark Kaplun Sep 11 '17 at 7:15
  • If I thought it was impossible I would not ask the question, there's nothing impossible. all the solutions I saw wasn't good enough.. – Avishay Sep 11 '17 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.