Here is the problem I am having:
- I have a custom post type called “weddingguests”
- This custom post type “weddingguests” has a custom taxonomy, “friendsof”, hierarchic
- I want to programmatically insert into this custom taxonomy “friendsof” 2 terms: “Friends of the Bride” and “Friends of the Groom”
Here is the function and the action I am using to insert one term:
// programatically add 2 terms to the taxonomy "FRIENDS OF"
function example_insert_category() {
wp_insert_term(
'Example Category',
'friendsof'
);
}
add_action( 'after_setup_theme', 'example_insert_category' );
The problem: wp_insert_term doesn’t appear to be working with my custom taxonomy
What I have tried:
- I have tried switching the taxonomy from hierarchic to non-hierarchic – that didn’t work
- I have tried using wp_insert_term (the same code) to add terms to the post “category” – that is working
- I have tried assigning the custom taxonomy “friendsof” to the posts and then add my term ( I thought there is a problem with the way I am building my custom post types) – that didn’t work
try init instead of after_setup_theme
While I don’t know why and don’t have time to investigate right now, the hook you’ve chosen is too early. Your code works if you use, for example,
init
instead ofafter_setup_theme
.In addition, as written, your code runs on every page load which is a bit profligate. There should be a way execute this only on plugin activation or perhaps on a change of theme– something that reduces the frequency this executes. Perhaps best case is a button in the theme/plugin to “Populate Defaults”. Once this runs once it is not needed anymore as the data is in the database.