WordPress插件没有例外行为

时间:2019-02-10 10:31:57

标签: wordpress plugins

下面的代码应该生成一个名为“ Zero Plugin Random”的插件,该插件在数据库中创建一个表。已检测到该插件并显示在管理面板中,但实际上未按例外方式创建该表。我在做错什么吗?

<?php
/*
Plugin Name: Zero PLugin Test
Plugin URI: http://zero-plugin.com
Description: Random Plugin
Version: 0.1
Author: Midnight Falcon
Author URI: http://website.com
License: GPL2
*/

class Zero{

  public static function init_table_members(){

    global $wpdb;
    $wpdb->query("CREATE TABLE IF NOT EXISTS {$wpdb->prefix}members;");

  }
  public function __construct(){
    register_activation_hook(__FILE__, [$this, 'init_table_members']);
  }
}

1 个答案:

答案 0 :(得分:0)

好吧,我相信代码缺少表结构,索引,并且类也没有实例化。

这里是如何在WordPress中创建自定义表的快速POC

<?php
/*
Plugin Name: Zero PLugin Test
Plugin URI: http://zero-plugin.com
Description: Random Plugin
Version: 0.1
Author: Midnight Falcon
Author URI: http://website.com
License: GPL2
*/

if ( ! defined('WPINC') ) die; // no direct access

register_activation_hook( __FILE__, 'my_plugin_create_db' );
function my_plugin_create_db() {

    global $wpdb;

  $charset_collate = $wpdb->get_charset_collate();

    $table_name = $wpdb->prefix . 'members';

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        views smallint(5) NOT NULL,
        clicks smallint(5) NOT NULL,
        UNIQUE KEY id (id)
    ) $charset_collate;";

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

}

以下是一些非常完整和说明性的指南:

https://deliciousbrains.com/creating-custom-table-php-wordpress/ https://pippinsplugins.com/create-database-tables-when-plugin-is-activated/

希望它会有所帮助;)