在WordPress插件激活上创建表(样板)

时间:2018-10-08 16:45:59

标签: php wordpress boilerplate

我正在尝试在激活m插件时创建表。我通过以下网址创建了插件:http://wppb.me/

这是我的代码,激活后没有出现错误,但是没有创建表。我需要在代码中的其他地方做其他事情吗?

   register_activation_hook( __FILE__,array( 'Horse_Exchange_Activator', 'activate' )  );


class Horse_Exchange_Activator {



    /**

     * Short Description. (use period)

     *

     * Long Description.

     *

     * @since    1.0.0

     */



    public static function activate() {


    global $table_prefix, $wpdb;

    $tblname = 'winners_horses';
    $wp_track_table = $table_prefix . "$tblname ";

    #Check to see if the table exists already, if not, then create it

    if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table) 
    {

        $sql = "CREATE TABLE `". $wp_track_table . "` ( ";
        $sql .= "  `id`  int(11)   NOT NULL auto_increment, ";
        $sql .= "  `horse`  varchar(255)   NOT NULL, ";
        $sql .= "  `event_name` varchar(255)   NOT NULL, "; 
        $sql .= "  `cloth` varchar(255)   NOT NULL, "; 
        $sql .= "  `posted` varchar(255)   NOT NULL, "; 
        $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 ; ";
        require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
        dbDelta($sql);



    }



}

1 个答案:

答案 0 :(得分:0)

您的主要问题是疾病。请仔细检查。这是解决方法。

<?php

/**
* Plugin Name: Test Plugin
*/


class Horse_Exchange_Activator {



    /**

     * Short Description. (use period)

     *

     * Long Description.

     *

     * @since    1.0.0

     */



    static function activate() {


        global $wpdb;
        $table_name = 'abctable';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
          id mediumint(9) NOT NULL AUTO_INCREMENT,
          time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
          name tinytext NOT NULL,
          text text NOT NULL,
          url varchar(55) DEFAULT '' NOT NULL,
          PRIMARY KEY  (id)
        ) $charset_collate;";

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



}

}


register_activation_hook( __FILE__,array( 'Horse_Exchange_Activator', 'activate' )  );