Wordpress: Create custom database tables


/ Published in: PHP
Save to your folder(s)

Create custom database tables within wordpress. Just replace 'stats' with the name of your table, and then the $sql variable with your create table sql.


Copy this code and paste it in your HTML
  1. function create_stats(){
  2. global $wpdb;
  3.  
  4. //create the name of the table including the wordpress prefix (wp_ etc)
  5. $search_table = $wpdb->prefix . "stats";
  6. //$wpdb->show_errors();
  7.  
  8. //check if there are any tables of that name already
  9. if($wpdb->get_var("show tables like '$search_table'") !== $search_table)
  10. {
  11. //create your sql
  12. $sql = "CREATE TABLE ". $search_table . " (
  13. stat_id mediumint(12) NOT NULL AUTO_INCREMENT,
  14. business_id mediumint(9),
  15. time VARCHAR (20) NOT NULL,
  16. user_ip text(20) NOT NULL,
  17. user_id mediumint(9),
  18. user_browser text NOT NULL,
  19. referral_page text NOT NULL,
  20. type text,
  21. UNIQUE KEY stat_id (stat_id));";
  22. }
  23.  
  24. //include the wordpress db functions
  25. require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
  26. dbDelta($sql);
  27.  
  28. //register the new table with the wpdb object
  29. if (!isset($wpdb->stats))
  30. {
  31. $wpdb->stats = $search_table;
  32. //add the shortcut so you can use $wpdb->stats
  33. $wpdb->tables[] = str_replace($wpdb->prefix, '', $search_table);
  34. }
  35. }
  36.  
  37. //add to front and backend inits
  38. add_action('init', 'create_stats');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.