Back to Snippets

Create a Custom Database Table

PHP Database & Queries April 6, 2026

Create a custom database table with dbDelta on theme activation. Includes proper charset, indexes, and an insert helper function.

Snippet Stats

Lines 44
Characters 1,241
Read 2 mins
php • 44 lines
/**
 * Create a custom database table on theme activation.
 *
 * @return void
 */
function mytheme_create_analytics_table(): void {
    global $wpdb;

    $table_name      = $wpdb->prefix . 'snippet_views';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        snippet_id BIGINT(20) UNSIGNED NOT NULL,
        user_ip VARCHAR(45) NOT NULL DEFAULT '',
        viewed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        KEY snippet_id (snippet_id),
        KEY viewed_at (viewed_at)
    ) {$charset_collate};";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}
add_action( 'after_switch_theme', 'mytheme_create_analytics_table' );

/**
 * Record a snippet view.
 *
 * @param int $snippet_id The snippet post ID.
 * @return void
 */
function mytheme_record_snippet_view( int $snippet_id ): void {
    global $wpdb;

    $wpdb->insert(
        $wpdb->prefix . 'snippet_views',
        array(
            'snippet_id' => $snippet_id,
            'user_ip'    => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' ),
        ),
        array( '%d', '%s' )
    );
}

Found an issue with this snippet? Help us improve by reporting it. Report it →

Related Snippets

View all
PHP
This snippet provides a custom WordPress hook to validate user registration, ensuring that users meet specific criteria before being allowed to regist...

WordPress Custom Hook For User Registration Validation

PHP
Build performant WP_Query with combined meta and taxonomy filters, numeric ordering, and no_found_rows optimization.

Optimized WP_Query with Meta and Tax Filters