drcomwc134525 2018-10-08 16:45
浏览 52
已采纳

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

I am trying to create a table when m plugin is activated. I created the plugin via here: http://wppb.me/

Here is my code, I don't get an errors when activated, however no tables are created. Do I need to do something else, elsewhere in the code?

   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条回答 默认 最新

  • duanhe7471 2018-10-08 17:31
    关注

    Your main problem is a condition. please check it very carefully. Here is solution.

    <?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' )  );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?