4

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:

// 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
  • do you have debugging enabled and have you tried inspecting the data that WordPress returns from wp_insert_term? – Milo Mar 6 '14 at 16:18
  • 2
    To insert a term in a taxonomy you must be sure that taxonomy is registered before the code that insert term runs. If you use 'after_setup_theme' to register the taxonomy, you should use a later hook to insert the terms. wp_loaded hook is best choice for such code. However, as @s_ha_dum suggests, you should put that code inside a conditional: if ( ! term_exists( 'example-category', 'friendsof' ) ) and trigger that code (i.e. put the add_action ) on theme switch or on plugin activation. – gmazzap Mar 6 '14 at 18:42
  • @gmazzap Thanks for that answer man, saved me a bunch of time. – Nathan Nov 18 '15 at 2:24
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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