“register_activation_hook” from another file

I’m new in wordpress and I want to add activation hook in my plugin. I want to run function not from the same file where activation hook placed. Is it possible? I tried so:

dy_ressel.php (main plugin file) :

Read More
$my_variable_for_identify_dir = plugin_dir_url( __FILE__ ) ;
register_activation_hook( $my_variable_for_identify_dir.'install.php','install_dy_ressel');

And install.php

function install_dy_ressel(){
        global $wpdb; 

        // Добавить к названию будущих табли префикс WP
        $table_users = $wpdb->prefix . "dy_users";


        // ПРоверка по наличию таблиц. Если нету или удалены - создать.

        if($wpdb->get_var("SHOW TABLES LIKE '$table_users'") != $table_users) {
            $sql = "CREATE TABLE " . $table_users . " (
              id mediumint(9) NOT NULL AUTO_INCREMENT,
              time bigint(11) DEFAULT '0' NOT NULL,
              name tinytext NOT NULL,
              text text NOT NULL,
              url VARCHAR(55) NOT NULL,
              UNIQUE KEY id (id)
            );";

            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }

Related posts

Leave a Reply

4 comments

  1. I want to run function not from the same file where activation hook placed.

    You answered your own question.

    You just need to place the activation hook in your main plugin file. But the function that it can be anywhere, so long as the file is included before it is called by WordPress.

    Your main plugin file might have:

    include( 'initialize-plugin.php' );
    register_activation_hook( __FILE__, 'install_dy_ressel' );
    

    And your initialize-plugin.php can have the function:

    function install_dy_ressel() {
        ...
    
  2. register_activation_hook doesn’t need to be called from the plugin’s main file, as long as you have some way of communicating the plugin’s main file’s path to that other piece of code. Here’s a simple way to do that:

    index.php (or whatever you call your plugin’s main file):

    define('MYPLUGIN_MAIN_FILE_PATH', __FILE__);
    require_once(__DIR__ . '/install.php');
    

    install.php:

    function install_my_plugin() {
      // do stuff.
    }
    register_activation_hook(MYPLUGIN_MAIN_FILE_PATH, 'install_my_plugin');
    
  3. dy_ressel.php

    include_once dirname( __FILE__ ).'/install.php';
    register_activation_hook( __FILE__, array( 'Register', 'install_dy_ressel' ) );
    

    install.php:

    Class Register {
        static function install_dy_ressel() {
            //register some short codes;
        }
        static function uninstall_dy_ressel {
            //unregister previous short codes;
        }
    }
    
  4. if your function is in a class
    $class = new Name_of_class(); //initialize it first

    include_once dirname( __FILE__ ).'/Name_of_class.php';
    register_activation_hook( __FILE__, array( $class, 'your_function' ) );