Support » Themes and Templates » Which is the best hook to use when creating a custom db table?

  • Hi all,

    I have a need to create a custom table from within my theme functions.php file, NOT from a plugin.

    I can just put the code in-line but suspect it would be more efficient to contain it in function that is called ideally just once, ever.

    So what is the best hook to use in this sample code?

    add_action( '<hook>', 'create_my_custom_table');

    Here are some options I think might work (I know init does, but isn’t it executed once for every user session?)


    Thanks, Ron

Viewing 1 replies (of 1 total)
  • While I’m on the subject of programatically creating tables, apparently there is a problem with dbDelta creating duplicate indexes. I am creating a table within the init action hook (for now) like this:

    function sv_create_favorites_table(){
    	global $wpdb;
    	$table_name = $wpdb->prefix . "favorites";
    	$sql = "CREATE TABLE IF NOT EXISTS $table_name (
    		fav_id bigint(20) not null auto_increment,
    		post_id bigint(20) not null,
    		user_id bigint(20) not null,
    		fav_date timestamp not null,
    		PRIMARY KEY  (fav_id),
    		KEY (post_id),
    		KEY (user_id)
    	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    add_action( 'init', 'sv_create_favorites_table');

    … and the only way I could prevent it from creating multiple duplicate indexes named post_id_2, 3, 4, etc was to add the “IF NOT EXISTS” clause to the CREATE TABLE statement.

    But the real question remains .. is there a better hook than init?, so that this create table statement is run exactly once as long as the site is alive (or I need to change it)?

Viewing 1 replies (of 1 total)
  • The topic ‘Which is the best hook to use when creating a custom db table?’ is closed to new replies.