Last active
June 26, 2019 12:08
-
-
Save bradt/dc67e8f91d1ce227f478 to your computer and use it in GitHub Desktop.
Managing Custom Tables in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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