WordPress.org

Ready to get started?Download WordPress

Forums

Which is the best hook to use when creating a custom db table? (2 posts)

  1. RonStrilaeff
    Member
    Posted 1 year ago #

    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?)

    init
    setup_theme
    after_setup_theme
    switch_theme
    after_switch_theme

    Thanks, Ron

  2. RonStrilaeff
    Member
    Posted 1 year ago #

    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');
    	dbDelta($sql);
    };
    
    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)?

Topic Closed

This topic has been closed to new replies.

About this Topic