How can I execute DB queries when theme installs and delete those tables on theme uninstall?

2 Answers 2


Yes, you can accomplish it by WP default functionality. Let me explain it.

1. While switch theme:

There is a switch_theme action that runs right after the theme is switched. switch_theme is triggered when the blog's theme is changed. Specifically, it fires after the theme has been switched but before the next request. Theme developers should use this hook to do things when their theme is deactivated.

<?php add_action('switch_theme', 'theme_deactivation_function'); ?> 

Theme functions attached to this hook are only triggered in the theme being deactivated. To do things when your theme is activated, use after_switch_theme.

Delete a theme's options after deactivation:

add_action('switch_theme', 'mytheme_setup_options');

function mytheme_setup_options () {

switch_theme will only be called when your theme is de-activated.

2. After switch theme:

Theme functions attached to this hook are only triggered in the theme (and/or child theme) being activated. To do things when your theme is deactivated, use switch_theme.

In other words, the after_setup_theme represents the point at which WordPress sets up the current Theme, not the point at which the administrator activates and/or configures the current Theme.

<?php add_action("after_switch_theme", "mytheme_do_something"); ?>

Add options for your theme and set them to their default values:

add_action('after_switch_theme', 'mytheme_setup_options');

function mytheme_setup_options () {
  add_option('mytheme_enable_catalog', 0);
  add_option('mytheme_enable_features', 0);

after_switch_theme only fire when your theme is being activated.

Referance: switch_theme and after_switch_theme actions hook are located in wp-includes/theme.php

  • This is for when you switch your theme. Deleting the theme options when switching to another one is can be a bad user experience since switching themes shouldn't be a destructive action. Apr 20, 2021 at 10:26

Theme activation use after_switch_theme

add_action("after_switch_theme", "setup_db"); 

function setup_db(){
   //run your create table statements

Theme deactivation use switch_theme

add_action('switch_theme', 'delete_db_things');

function delete_db_things(){
  //run deletion statements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.