wp_insert_term doesn’t work with custom post type’s taxonomy

Here is the problem I am having:

  1. I have a custom post type called “weddingguests”
  2. This custom post type “weddingguests” has a custom taxonomy, “friendsof”, hierarchic
  3. 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:

Read More
// 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:

  1. I have tried switching the taxonomy from hierarchic to non-hierarchic – that didn’t work
  2. I have tried using wp_insert_term (the same code) to add terms to the post “category” – that is working
  3. 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

Related posts

2 comments

  1. try init instead of after_setup_theme

    function example_insert_category() {
        wp_insert_term(
            'Example Category',
            'friendsof'
        );
    }
    
    add_action( 'init', 'example_insert_category' );
    
  2. 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 of after_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.

Comments are closed.