Created
December 14, 2016 06:09
-
-
Save prajwal-stha/7cf3ab9925fbecd03b98af993e23bfdc to your computer and use it in GitHub Desktop.
Managing Custom Table in WordPress [Source: https://deliciousbrains.com/managing-custom-tables-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 | |
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