$wpdb写的查询数据库的小插件

Published
April 21, 2022
浏览次数 :  4

if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
require_once plugin_dir_path(__FILE__) . 'inc/generatePet.php';

class PetAdoptionTablePlugin {
  function __construct() {
    global $wpdb;
    $this->charset = $wpdb->get_charset_collate();
    $this->tablename = $wpdb->prefix . "pets";
    //插件启动时候的钩子 
    register_activation_hook( __FILE__, array($this,'onActivate' ));
    //等同于 
    //add_action('activate_new-database-table/new-database-table.php', array($this, 'onActivate'));
    //每次刷新admin页面的时候执行函数。  @hook https://developer.wordpress.org/reference/hooks/admin_head/
    //add_action('admin_head', array($this, 'populateFast'));
    add_action('admin_post_nopriv_createpet',array($this,'createPet'));
    add_action('admin_post_createpet',array($this,'createPet'));
    add_action('admin_post_nopriv_deletepet',array($this,'deletePet'));
    add_action('admin_post_deletepet',array($this,'deletePet'));
    add_action('wp_enqueue_scripts', array($this, 'loadAssets'));
    add_filter('template_include', array($this, 'loadTemplate'), 99);
  }
  function createPet() {
    if(current_user_can( 'administrator' )) {
      $pet = generatePet();
      $pet['petname'] = sanitize_text_field($_POST['incomingPetName']);
      global $wpdb;
      $wpdb->insert($this->tablename,$pet);
      wp_redirect(site_url('/pet-adoption'));
    } else {
      wp_redirect( site_url());
    }
    exit;

  }

  function deletePet() {
    if(current_user_can( 'administrator' )) {
      $id = sanitize_text_field($_POST['idtodelete']);
      global $wpdb;
      $wpdb->delete($this->tablename,array('id' => $id));
      wp_safe_redirect(site_url('/pet-adoption'));
    } else {
      wp_safe_redirect( site_url());
    }
    exit;
  }
  function onActivate() {
    //wordpress function
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta( "CREATE TABLE $this->tablename (
      id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      birthyear smallint(5) NOT NULL DEFAULT 0,
      petweight smallint(5) NOT NULL DEFAULT 0,
      petname varchar(60) NOT NULL DEFAULT '',
      species varchar(60) NOT NULL DEFAULT '',
      favcolor varchar(60) NOT NULL DEFAULT '',
      favfood varchar(60) NOT NULL DEFAULT '',
      favhobby varchar(60) NOT NULL DEFAULT '',   
      PRIMARY KEY  (id)  
) $this->charset;");

  }

  function onAdminRefresh() {
    //insert record to table  NOTICE:每次刷新的时候新增一行数据
    global $wpdb;

    //insert method include two paremeters first is the table name insert record to ,second is the array,the acutual data you want to save 
    //
    $wpdb->insert($this->tablename,generatePet());
    
  }



  function loadAssets() {
    if (is_page('pet-adoption')) {
      wp_enqueue_style('petadoptioncss', plugin_dir_url(__FILE__) . 'pet-adoption.css');
    }
  }

  function loadTemplate($template) {
    //if is page pet-adoption use the inc/template-pets.php template else use the default template for the wordpress url 
    if (is_page('pet-adoption')) {
      return plugin_dir_path(__FILE__) . 'inc/template-pets.php';
    }
    return $template;
  }

  function populateFast() {
    $query = "INSERT INTO $this->tablename (`species`, `birthyear`, `petweight`, `favfood`, `favhobby`, `favcolor`, `petname`) VALUES ";
    $numberofpets = 1000;
    for ($i = 0; $i < $numberofpets; $i++) {
      $pet = generatePet();
      $query .= "('{$pet['species']}', {$pet['birthyear']}, {$pet['petweight']}, '{$pet['favfood']}', '{$pet['favhobby']}', '{$pet['favcolor']}', '{$pet['petname']}')";
      if ($i != $numberofpets - 1) {
        $query .= ", ";
      }
    }
    /*
    Never use query directly like this without using $wpdb->prepare in the
    real world. I'm only using it this way here because the values I'm 
    inserting are coming fromy my innocent pet generator function so I
    know they are not malicious, and I simply want this example script
    to execute as quickly as possible and not use too much memory.
    */
    global $wpdb;
    $wpdb->query($query);
  }

}

$petAdoptionTablePlugin = new PetAdoptionTablePlugin();

Top