AfterSwitchTheme Video Tutorial
In this chapter I suggest you answer a question that was asked by a user on the video on taxonomy.
Is it possible to automatically create the names of the categories you want when you install WP without having to go through the administration panel. For example automatically create: football, tennis, etc?
Even if it is not necessarily difficult to find the function which makes it possible to insert key words, one can wonder where to place the logic. It would be necessary to detect when the theme is activated by the user and insert the basic data at that time.
after_switch_theme
It is possible to detect when our theme is activated thanks to the hook after_switch_theme
.
add_action ('after_switch_theme', function () {
wp_insert_term ('Football', 'sport');
wp_insert_term ('Football', 'sport');
});
Here the function wp_insert_term ()
will not create a duplicate because it checks the existence of the keyword but if you use a different logic think of not creating duplicates because it is possible that this function is called several times if the user changes the theme several times.
Also, if you are using custom content types I recommend calling the function flush_rewrite_rules ()
which will refresh the writing rules and ensure that your redirection rules are taken into account.
add_action ('after_switch_theme', 'flush_rewrite_rules');
add_action ('switch_theme', 'flush_rewrite_rules');