Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bradt
Last active June 26, 2019 12:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save bradt/dc67e8f91d1ce227f478 to your computer and use it in GitHub Desktop.
Save bradt/dc67e8f91d1ce227f478 to your computer and use it in GitHub Desktop.
Managing Custom Tables in WordPress
<?php
class WPAS_Model_Order_Meta extends WPAS_Model {
static $primary_key = 'order_id';
static function set_as_refunded( $order_id ) {
$data = array( 'is_refunded' => 1 );
$where = array( 'order_id' => $order_id );
self::update( $data, $where );
}
static function set_as_test( $order_id ) {
$data = array( 'is_test' => 1 );
$where = array( 'order_id' => $order_id );
self::update( $data, $where );
}
}
<?php
abstract class WPAS_Model {
static $primary_key = 'id';
private static function _table() {
global $wpdb;
$tablename = strtolower( get_called_class() );
$tablename = str_replace( 'wpas_model_', 'wpas_', $tablename );
return $wpdb->prefix . $tablename;
}
private static function _fetch_sql( $value ) {
global $wpdb;
$sql = sprintf( 'SELECT * FROM %s WHERE %s = %%s', self::_table(), static::$primary_key );
return $wpdb->prepare( $sql, $value );
}
static function get( $value ) {
global $wpdb;
return $wpdb->get_row( self::_fetch_sql( $value ) );
}
static function insert( $data ) {
global $wpdb;
$wpdb->insert( self::_table(), $data );
}
static function update( $data, $where ) {
global $wpdb;
$wpdb->update( self::_table(), $data, $where );
}
static function delete( $value ) {
global $wpdb;
$sql = sprintf( 'DELETE FROM %s WHERE %s = %%s', self::_table(), static::$primary_key );
return $wpdb->query( $wpdb->prepare( $sql, $value ) );
}
static function insert_id() {
global $wpdb;
return $wpdb->insert_id;
}
static function time_to_date( $time ) {
return gmdate( 'Y-m-d H:i:s', $time );
}
static function now() {
return self::time_to_date( time() );
}
static function date_to_time( $date ) {
return strtotime( $date . ' GMT' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment