0

I suspect the way I call the table creation function below is the culprit for no table creation (nothing shows in the debug log or query array). Can anyone see my mistake?

// main plugin file, frequentVisitorCoupons.php
require 'vendor/autoload.php';

// the first argument points to this file because I think
// autoload automatically loads the Utilities class here
register_activation_hook(plugin_dir_url(__FILE__) . 'frequentVisitorCoupons.php',
 'Utilities::createTablesIfNotExists');


// classes/utilities.php
<?php    
class Utilities {
  public static function createTablesIfNotExists() {
    global $wpdb;

    $createCouponTableQuery = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}frequentVisitorCoupons_coupons (
    couponId MEDIUMINT NOT NULL AUTO_INCREMENT UNIQUE,
    PRIMARY KEY  (couponId),
    totalHits MEDIUMINT NOT NULL,
    isText BOOLEAN NOT NULL,
    imageUrl TEXT(1000)
    )";

    <2 more table create queries removed>

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

    var_dump($wpdb->queries);
    echo <<<'EOD'
    =====$wpdb->queries=====
EOD;
  }
}
2

plugin_dir_url() returns the URL directory path for your plugin, so this won't work as expected (the function won't be called):

register_activation_hook(plugin_dir_url(__FILE__) . 'frequentVisitorCoupons.php',
 'Utilities::createTablesIfNotExists');

You should have used plugin_dir_path() which returns the file-system directory path for your plugin (e.g. /var/www/public/<user>/wp-content/plugins/your-plugin/).

But if the code is in the main plugin file, then you could simply use __FILE__:

register_activation_hook(__FILE__, 'Utilities::createTablesIfNotExists');

Sample plugin main file:

<?php
/*
 * Plugin Name: My Plugin
 */

require_once 'path/to/classes/utilities.php';

// Installs the tables on plugin activation.
register_activation_hook( __FILE__, 'Utilities::createTablesIfNotExists' );

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.