Wordpress: register_activation_hook not working

Asked
Active3 hr before
Viewed126 times

9 Answers

wordpressworking
90%

Here the point is register_activation_hook( $file, $function );,Reference: https://codex.wordpress.org/Function_Reference/register_activation_hook,The register_activation_hook call needs to be outside of the class itself.,In order to work register_activation_hook OR register_deactivation_hook the functions should be in index file OR we need to specify the full path to the file argument.

Back to the WordPress documentation.

< ? php register_activation_hook($file, $function); ? >

your_main_plugin_file.php

define(PLUGIN_FILE_URL, __FILE__);

includes/some_file.php

< ? php register_activation_hook(PLUGIN_FILE_URL, ['your_class_name_here', 'your_class_method_name_here']); ? >

or if you use functions instead of classes then do

< ? php register_activation_hook(PLUGIN_FILE_URL, 'your_function_name_here'); ? >
load more v
88%

I am writing a plugin that on the activation must create a new table in database., What does FILE means in register_activation_hook( FILE, 'createTable' );? Are code fragments you've pasted both resides in the main plugin file? – Max Yudin Feb 21 '13 at 12:35 ,When i run the activation, my plugin creates the new table in the database but when the plugin-page is reloaded my plugin is listed as not active. So i have still the links:, 1 activating debug mode in wp-config, when i try to activate my plugin i get this message:The plugin generated 754 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin. – Salvatore Dibenedetto Feb 21 '13 at 13:32

Works perfectly when this code is in main plugin file:

< ? php

function createTable() {
   global $wpdb;
   $query = "CREATE TABLE IF NOT EXISTS ".$wpdb - > prefix.
   "UsersExtra (
   user_id INT NOT NULL,
   first_name VARCHAR(25) NOT NULL,
      last_name VARCHAR(25) NOT NULL,
      address VARCHAR(80) NOT NULL,
      city VARCHAR(30) NOT NULL,
      province CHAR(2) NOT NULL,
      postcode CHAR(7) NOT NULL,
      interests TEXT NULL,
      bio TEXT NULL,
      signature TEXT NULL,
      skills TEXT NULL,
      PRIMARY KEY(user_id),
      FULLTEXT KEY(interests, skills)
) ENGINE = MyISAM DEFAULT CHARSET = utf8 ";
$wpdb - > query($query);
}
register_activation_hook(__FILE__, 'createTable');
72%

You can check out the full post @ http://stackoverflow.com/questions/7738953/is-there-a-way-to-determine-if-a-wordpress-plugin-is-just-installed/13927297#13927297.,Included plugin files and even other plugins will be able to hook into this action.,Registering the hook inside the ‘plugins_loaded’ hook will not work. You can’t call register_activation_hook() inside a function hooked to the 'plugins_loaded' or 'init' hooks (or any other hook). These hooks are called before the plugin is loaded or activated.,However, if you try to add register_activation_hook() in the constructor of the class it won’t work because it’s not in the main plugin file.

If you are interested in doing something just after a plugin has been activated it is important to note that the hook process performs an instant redirect after it fires. So it is impossible to use add_action() or add_filter() type calls until the redirect has occurred (e.g., only two hooks are fired after the plugin’s activation hook: 'activated_plugin' and 'shutdown'). A quick workaround to this quirk is to use add_option() like so:

/* Main Plugin File */
...
function my_plugin_activate() {

   add_option('Activated_Plugin', 'Plugin-Slug');

   /* activation code here */
}
register_activation_hook(__FILE__, 'my_plugin_activate');

function load_plugin() {

   if (is_admin() && get_option('Activated_Plugin') == 'Plugin-Slug') {

      delete_option('Activated_Plugin');

      /* do stuff once right after activation */
      // example: add_action( 'init', 'my_init_function' );
   }
}
add_action('admin_init', 'load_plugin');

However, it is possible to use do_action(), like this:

function my_plugin_activate() {

   do_action('my_plugin_activate');
}
register_activation_hook(__FILE__, 'my_plugin_activate');

If you’re using global variables, you may find that the function you pass to register_activation_hook() does not have access to global variables at the point when it is called, even though you state their global scope within the function like this:

$myvar = 'whatever';

function myplugin_activate() {

   global $myvar;
   echo $myvar; // this will NOT be 'whatever'!
}

register_activation_hook(__FILE__, 'myplugin_activate');

When activation occurs, your plugin is included from another function and then your myplugin_activate() is called from within that function (specifically, within the activate_plugin() function) at the point where your plugin is activated. The main body variables are therefore in the scope of the activate_plugin() function and are not global, unless you explicitly declare their global scope:

global $myvar;
$myvar = 'whatever';

function myplugin_activate() {

   global $myvar;
   echo $myvar; // this will be 'whatever'
}
register_activation_hook(__FILE__, 'myplugin_activate');
load more v
65%

Wordpress register_activation_hook table creation not working,If you see, I call the function in the activation method in my main file. But when I activate the plugin there is no new table in my database. ,Does anyone have a idea why? Is there a way to debug the register_activation_hook?,In the folder ´inc´ I have a DatabaseUtils.php file. This is a class with a function to create a table in the wordpress database after activating the plugin. Here the content:

I've created a simple Class for my wordpress plugin. The main file looks like this:

< ? php
/*
 * Plugin Name: Codes
 * Description: Generates a coupon code after checkout
 * Version: 0.1.0
 * Author: XXX
 */

require_once('inc/DatabaseUtils.php');

$codes = new Codes();

class Codes {

   private $databaseUtils;

   /**
    * Create a new instance 
    *
    * @param null
    * @return void
    */
   function __construct() {
      $this - > regsiter_hooks();
      $this - > databaseUtils = new DatabaseUtils();
   }

   /**
    * Called on plugin activation
    *
    * @param null
    * @return void
    */
   function activate() {
      $this - > databaseUtils - > setup_codes_table();
   }

   /**
    * Called on plugin deactivation
    *
    * @param null
    * @return void
    */
   function deactivate() {

   }

   /**
    * Register plugin hooks
    *
    * @param null
    * @return void
    */
   function regsiter_hooks() {
      register_activation_hook(__File__, array($this, 'activate'));
      register_deactivation_hook(__File__, array($this, 'deactivate'));
   }
}

In the folder ´inc´ I have a DatabaseUtils.php file. This is a class with a function to create a table in the wordpress database after activating the plugin. Here the content:

< ? php

class DatabaseUtils {

   function setup_codes_table() {
      global $wpdb;
      global $charset_collate;
      $table_name = $wpdb - > prefix.
      'pin';
      $sql = "CREATE TABLE IF NOT EXISTS $table_name (
      `id`
      bigint(20) NOT NULL AUTO_INCREMENT,
         `pincode`
      bignit(128) DEFAULT NOT NULL,
         PRIMARY KEY(`id`)
   ) $charset_collate;
   ";
   require_once(ABSPATH.
      'wp-admin/includes/upgrade.php');
   dbDelta($sql);
}

}
load more v
75%

I currently writing a wordpress plugin, and i encountered some problem. my function does not run upon plugin activation... can somebody tell me where is the proble?,Please check if you're using softlink, the plugin must exactly in /path/to/wordpress/wp-content/plugins/yourplugin, meaning to say that yourplugin is not a softlink.,You have Wordpress trying to call a function called install in your class, but it doesn't exist. So try changing:,From the posted code I can see two problems. install should be changed to wpmon_install. Also you should add some code to initialize your class.

I currently writing a wordpress plugin, and i encountered some problem. my function does not run upon plugin activation... can somebody tell me where is the proble?

class my_plugin {

   public $ajaxurl;
   public $excanvas;
   public $plugin_path = '';

   function __construct() {

      register_activation_hook(__FILE__, array( & $this, 'install'));
   }

   public
   function wpmon_install() {
      //Copy my page template to current theme.

      $plugin_path = getcwd().DIRECTORY_SEPARATOR.
      'wp-content'.DIRECTORY_SEPARATOR.
      'plugins'.DIRECTORY_SEPARATOR.
      'wpmon'.DIRECTORY_SEPARATOR;
      $target_path = get_stylesheet_directory().DIRECTORY_SEPARATOR;
      $target_path = str_replace('/', DIRECTORY_SEPARATOR, $target_path);
      $template_files = glob($plugin_path.
         'page_template'.DIRECTORY_SEPARATOR.
         '*.php');

      foreach($template_files as $files) {
         $basename = basename($files);
         try {
            $target = $target_path.$basename;
            copy($files, $target);

         } catch (Exception $e) {

            $this - > log_error($e - > getMessage());
         }
      }
   }
load more v
40%

So I had an issue with my wordpress plugin not getting initialised properly, my activation hook was not working correctly. If you are in a hurry, my fix was this:,For more in depth trouble shooting, here are some things to know about the wordpress plugin activation process.,If it working correctly it should appear as above, otherwise it will look something like,When you call register_activation_hook() it adds an action to the list with your callback associated with it. The action name is something like

When you call register_activation_hook() it adds an action to the list with your callback associated with it. The action name is something like

activate_test.php
load more v
22%

if (isset($_POST['submit'])) {

   global $wpdb;
   $tablename = $wpdb - > prefix.
   'post_job';

   $wpdb - > insert($tablename, array(
         'organizationname' => $_POST['organizationname'],
         'post' => $_POST['post'],
         'publishfrom' => $_POST['publishfrom'],
         'publishupto' => $_POST['publishupto'],
         'qualification1' => $_POST['qualification1'],
         'qualification2' => $_POST['qualification2'],
         'qualification3' => $_POST['qualification3'],
         'qualification4' => $_POST['qualification4'],
         'experience1' => $_POST['experience1'],
         'experience2' => $_POST['experience2'],
         'experience3' => $_POST['experience3'],
         'training1' => $_POST['training1'],
         'training2' => $_POST['training2'],
         'training3' => $_POST['training3'],
         'training4' => $_POST['training4'],
         'training5' => $_POST['training5']),
      array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
   );
}
load more v
60%

 /**
  * Constructor for the Anthologize class
  *
  * This constructor does the following:
  * - Checks minimum PHP and WP version, and bails if they're not met
  * - Includes Anthologize's main files
  * - Sets up the basic hooks that initialize Anthologize's post types and UI
  *
  * @since 0.7
  */
 public
 function __construct() {
    // Bail if PHP version is not at least 5.0
    if (!self::check_minimum_php()) {
       add_action('admin_notices', array('Anthologize', 'phpversion_nag'));
       return;
    }
    // Bail if WP version is not at least 3.3
    if (!self::check_minimum_wp()) {
       add_action('admin_notices', array('Anthologize', 'wpversion_nag'));
    }
    // If we've made it this far, start initializing Anthologize
    register_activation_hook(__FILE__, array($this, 'activation'));
    register_deactivation_hook(__FILE__, array($this, 'deactivation'));
    // @todo WP's functions plugin_basename() etc don't work
    //   correctly on symlinked setups, so I'm implementing my own
    $bn = explode(DIRECTORY_SEPARATOR, dirname(__FILE__));
    $this - > basename = array_pop($bn);
    $this - > plugin_dir = plugin_dir_path(__FILE__);
    $this - > plugin_url = plugin_dir_url(__FILE__);
    $this - > includes_dir = trailingslashit($this - > plugin_dir.
       'includes');
    $upload_dir = wp_upload_dir();
    $this - > cache_dir = trailingslashit($upload_dir['basedir'].
       '/anthologize-cache');
    $this - > cache_url = trailingslashit($upload_dir['baseurl'].
       '/anthologize-cache');
    $this - > setup_constants();
    $this - > includes();
    $this - > setup_hooks();
 }
load more v
48%

WordPress database is beautifully crafted so that in most cases we don’t need to create a custom database table. But on some occasions, if you need to do that then how you can create the custom database table in WordPress?,We hope this article helped you to create database table in WordPress.,Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!, WordPress: Create Reset Password Link

CREATE TABLE[IF NOT EXISTS] table_name(
   column_1_definition,
   column_2_definition,
   ...,
   table_constraints
) ENGINE = storage_engine;
load more v

Other "wordpress-working" queries related to "Wordpress: register_activation_hook not working"