admin管理员组

文章数量:1317572

I started building a plugin in which I need to build some custom queries with wpdb object. It's the first time I use it. So I checked out how to use it. I watched some examples and there is something which is messing up my mind : upgrade.php

Actually when I create a custom query, this one only works when I include upgrade.php this way :

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$custom_posts = $wpdb->get_results( 'SELECT * FROM ' . self::TABLE . '', OBJECT_K );
$wpdb->show_errors();
echo $wpdb->last_query;
return $custom_posts;

This is just one of the method's example I can privide.

What is the use of upgrade.php ? I mean, if I don't put it, the query doesn't work. Could someone explain, please, cause there's nothing in the codex concerning that.

Am I really oblidged to use it ? why ? How ?

Thanks

UPDATE : Here is the complete code.

/**
 * On activate or uninstall plugin
 */
register_activation_hook( __FILE__, array( 'Cpt', 'init' ) );
register_deactivation_hook( __FILE__, array( 'Cpt', 'uninit' ) );
register_uninstall_hook( __FILE__, array( 'Cpt', 'uninit' ) );

global $wpdb;

class Cpt
{

    CONST TABLE = 'cpt';

    /**
     * Constructor
     */
    public function init()
    {
        /**
         * Creation table for cpt
         */
        $sql = "CREATE TABLE IF NOT EXISTS `" . self::TABLE . "` (
          id mediumint(9) NOT NULL AUTO_INCREMENT,
          time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
          name tinytext NOT NULL,
          UNIQUE KEY id (id)
        );";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->query($sql);

        self::convert_to('post', 'custom');
    }

    public function uninit() {
        /**
         * Delete table for cpt
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        //$wpdb->query("DROP TABLE IF EXISTS `cpt`;");
        //$this->delete_cpt("Custom post 1");
    }

    /**
     * Add a custom post type
     */
    public function add_cpt($name) {
        /**
         * Add a single data
         */
        $time = (string)date('dmY');
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->insert( 
            self::TABLE, 
            array(
                'time'=>$time, 
                'name'=>$name
            ) 
        );
        /*$wpdb->show_errors();
        echo $wpdb->last_query;
        die();*/
    }

    /**
     * Delete a custom post type
     */
    public function delete_cpt($name) {
        /**
         * delete a single data
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->delete( 
            self::TABLE, 
            array( 
                'name'=>$name 
            ) 
        );
        $wpdb->show_errors();
        echo $wpdb->last_query;
        die();
    }

    /**
     * Get all custom post types
     */
    public static function get_ctps() {
        /**
         * delete a single data
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $custom_posts = $wpdb->get_results( 'SELECT * FROM ' . self::TABLE . '', OBJECT_K );
        $wpdb->show_errors();
        echo $wpdb->last_query;
        return $custom_posts;
    }

    /**
     * Get a single custom post type
     */
    public function get_ctp($name) {
        /**
         * get a single data
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $custom_post = $wpdb->get_results( 'SELECT name FROM ' . self::TABLE . ' WHERE name = $name', OBJECT_K );
        $wpdb->show_errors();
        echo $wpdb->last_query;
        print_r($custom_post);
        //return $custom_post;
    }

    /**
     * Post type conversion
     */
    public static function convert_to($from, $to) {

        // Get the posts of the type $from
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->update( 'wp_posts', array('post_type'=>$to), array('post_type'=>$from) );
        $wpdb->show_errors();
        echo $wpdb->last_query;
    }

    /**
     * Generate admin menu with all custom post types
     */
    public function generate_menu() {

        $custom_posts = self::get_ctps(); 
    }
}

I started building a plugin in which I need to build some custom queries with wpdb object. It's the first time I use it. So I checked out how to use it. I watched some examples and there is something which is messing up my mind : upgrade.php

Actually when I create a custom query, this one only works when I include upgrade.php this way :

require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$custom_posts = $wpdb->get_results( 'SELECT * FROM ' . self::TABLE . '', OBJECT_K );
$wpdb->show_errors();
echo $wpdb->last_query;
return $custom_posts;

This is just one of the method's example I can privide.

What is the use of upgrade.php ? I mean, if I don't put it, the query doesn't work. Could someone explain, please, cause there's nothing in the codex concerning that.

Am I really oblidged to use it ? why ? How ?

Thanks

UPDATE : Here is the complete code.

/**
 * On activate or uninstall plugin
 */
register_activation_hook( __FILE__, array( 'Cpt', 'init' ) );
register_deactivation_hook( __FILE__, array( 'Cpt', 'uninit' ) );
register_uninstall_hook( __FILE__, array( 'Cpt', 'uninit' ) );

global $wpdb;

class Cpt
{

    CONST TABLE = 'cpt';

    /**
     * Constructor
     */
    public function init()
    {
        /**
         * Creation table for cpt
         */
        $sql = "CREATE TABLE IF NOT EXISTS `" . self::TABLE . "` (
          id mediumint(9) NOT NULL AUTO_INCREMENT,
          time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
          name tinytext NOT NULL,
          UNIQUE KEY id (id)
        );";
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->query($sql);

        self::convert_to('post', 'custom');
    }

    public function uninit() {
        /**
         * Delete table for cpt
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        //$wpdb->query("DROP TABLE IF EXISTS `cpt`;");
        //$this->delete_cpt("Custom post 1");
    }

    /**
     * Add a custom post type
     */
    public function add_cpt($name) {
        /**
         * Add a single data
         */
        $time = (string)date('dmY');
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->insert( 
            self::TABLE, 
            array(
                'time'=>$time, 
                'name'=>$name
            ) 
        );
        /*$wpdb->show_errors();
        echo $wpdb->last_query;
        die();*/
    }

    /**
     * Delete a custom post type
     */
    public function delete_cpt($name) {
        /**
         * delete a single data
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->delete( 
            self::TABLE, 
            array( 
                'name'=>$name 
            ) 
        );
        $wpdb->show_errors();
        echo $wpdb->last_query;
        die();
    }

    /**
     * Get all custom post types
     */
    public static function get_ctps() {
        /**
         * delete a single data
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $custom_posts = $wpdb->get_results( 'SELECT * FROM ' . self::TABLE . '', OBJECT_K );
        $wpdb->show_errors();
        echo $wpdb->last_query;
        return $custom_posts;
    }

    /**
     * Get a single custom post type
     */
    public function get_ctp($name) {
        /**
         * get a single data
         */
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $custom_post = $wpdb->get_results( 'SELECT name FROM ' . self::TABLE . ' WHERE name = $name', OBJECT_K );
        $wpdb->show_errors();
        echo $wpdb->last_query;
        print_r($custom_post);
        //return $custom_post;
    }

    /**
     * Post type conversion
     */
    public static function convert_to($from, $to) {

        // Get the posts of the type $from
        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        $wpdb->update( 'wp_posts', array('post_type'=>$to), array('post_type'=>$from) );
        $wpdb->show_errors();
        echo $wpdb->last_query;
    }

    /**
     * Generate admin menu with all custom post types
     */
    public function generate_menu() {

        $custom_posts = self::get_ctps(); 
    }
}
Share Improve this question edited Jul 15, 2014 at 16:24 Neovea asked Jul 14, 2014 at 15:13 NeoveaNeovea 1492 silver badges10 bronze badges 6
  • 1 what is the context of this code? are you trying to use the WordPress API in a directly loaded php file? if your plugin is properly structured, you only need upgrade.php for table creation and modification. – Milo Commented Jul 14, 2014 at 16:00
  • Yes actually the first time I used it, it was to create a table in a choosen database. But it seems like if don't use it aswell to add datas or select datas in/from de db, it doesn't work. And if I put this code, it works. But as I didn't understand very well how and why, it's hard to say... – Neovea Commented Jul 14, 2014 at 16:49
  • where is this code and how is it loaded by your plugin? – Milo Commented Jul 14, 2014 at 18:42
  • I'll send you that as soon as possible. – Neovea Commented Jul 14, 2014 at 18:47
  • I just edited my question in order to let you see the entire code. – Neovea Commented Jul 15, 2014 at 16:25
 |  Show 1 more comment

2 Answers 2

Reset to default 2

No, and in fact you should not include the wp-admin/includes/upgrade.php file in a plugin. There is no real valid use case for doing so. It doesn't do anything for you or add any useful functions for a plugin.

As for your question, you say "it doesn't work" but you fail to define what that means. Providing the error messages you receive is useful when you're asking questions.

I do note that in a number of functions, you're trying to call the functionality in $wpdb without declaring global $wpdb; first. Try replacing the require_once with that instead.

In the context of your code the inclusion has no use but, to answer your question in another way, upgrade.php is a file that defines the dbDelta() function, which can be used to upgrade a MySQL table if it allready exists. This mechanism comes in handy when upgrading a plugin to a version that uses different MySQL tables without loss of data.

The default way of creating a custom MySQL table when installing a plugin, is stated here:
source: Codex - Creating Tables with Plugins

The next step is to actually create the database table. Rather than executing an SQL query directly, we'll use the dbDelta function in wp-admin/includes/upgrade.php (we'll have to load this file, as it is not loaded by default). The dbDelta function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary, so it can be very handy for updates (see wp-admin/upgrade-schema.php for more examples of how to use dbDelta)

So you may want to ditch the query() method in favor of the dbDelta function(), keeping the file inclusion.

本文标签: queryThe use of including upgradephp when building custom queries