Skip to content

Instantly share code, notes, and snippets.

@Magnacarter
Last active November 6, 2019 21:57
Show Gist options
  • Save Magnacarter/f3d8f50b6af886430dd79aa39c44583f to your computer and use it in GitHub Desktop.
Save Magnacarter/f3d8f50b6af886430dd79aa39c44583f to your computer and use it in GitHub Desktop.
How to build a WP custom db table
<?php
/**
* Install placement table
* upon plugin activation, create custom table to store user placements
*
* @since 4.0.0
* @author acarter
*
* @return void
*/
function install_placement_table() {
// Get the wpdb object
global $wpdb;
// Name the table
$table_prefix = $wpdb->base_prefix;
$table_name = $table_prefix . 'peta_placements';
$wpdb->peta_placements = $table_name;
// Get the charset
$charset_collate = $wpdb->get_charset_collate();
// Build the table
// If you want you can add NOT NULL so the field has to be set.
// Example, the id for the thing you want to keep track of so it can be called easy from the
// the db would require and ID.
// Be sure to set that ID as the primary key for the table with PRIMARY KEY (name_of_your_id)
$sql = "CREATE TABLE $table_name (
placement_id mediumint(9) NOT NULL,
pos_order_number text NOT NULL,
placement_order text,
placement_name text,
post_types text,
categories text,
taxonomies text,
last_update text,
placement_url varchar(100) DEFAULT '' NOT NULL,
PRIMARY KEY (placement_id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
// Run the function somewhere, functions.php etc...
/**
* Check to see if the site already has placement table installed
* Nice way to create a bool check for a table's existence.
*
* @since. 4.0.0
* @author adamc
*
* @return bool
*/
function has_placement_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'your_table_name';
$table_check = $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" );
if ( isset( $table_check ) ) {
return true;
} else {
return false;
}
}
// See here how I implement a custom table for plugin-placement
// https://github.com/PETAF/plugin-placement/blob/placement-version-4.0/inc/class-custom-tables.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment