Search code examples
wordpresscustom-post-typetaxonomy-terms

How to create taxonomy term when creating the taxonomy through a custom plugin?


I am trying to add Taxonomy Term pragmatically when creating taxonomy. I tried adding the

wp_insert_term(
    'A00',   // the term 
    'we_colors'
);

to the tax_color_palletes but this is not adding the term A00. I am working on this snippet; how can I fix this?

function tax_color_palletes() {

    $labels = array(
        'name'                       => 'Models',
        'singular_name'              => 'Model',
        'menu_name'                  => 'Models',
        'all_items'                  => 'All Models',
        'parent_item'                => 'Parent Model',
        'parent_item_colon'          => 'Parent Model',
        'new_item_name'              => 'Model Name',
        'add_new_item'               => 'Add New Model',
        'edit_item'                  => 'Edit Model',
        'update_item'                => 'Update Model Type',
        'separate_items_with_commas' => 'Separate Model with commas',
        'search_items'               => 'Search Models',
        'add_or_remove_items'        => 'Add or remove Model Type',
        'choose_from_most_used'      => 'Choose from the most used Model',
        'not_found'                  => 'Model Not Found',
    );
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
    );
    register_taxonomy( 'women_models', array( 'we_colors' ), $args );
    wp_insert_term(
        'A00',   // the term 
        'we_colors'
    );
}
add_action( 'init', 'tax_color_palletes', 0 );

Solution

  • Are you trying to add the term to your taxonomy or post_type?

    In your example you register the taxonomy 'women_models' to the post_type 'we_colors'. But then you call wp_insert_term (which requires a taxonomy) and pass it a post_type. Which should give you an error.

    If you want to just add a term to a taxonomy, you need to pass your taxonomy to wp_insert_term.

    wp_insert_term('A00', 'women_models');
    

    If instead you are actually trying to add a term to a post_type, you should use wp_set_object_terms which can in turn call wp_insert_term itself to create new terms. You will need to get the $object_id first however.

    wp_set_object_terms( $object_id, ['term_1', 'term_2'], 'taxonomy_name');
    

    https://developer.wordpress.org/reference/functions/register_taxonomy/ https://developer.wordpress.org/reference/functions/wp_insert_term/ https://developer.wordpress.org/reference/functions/wp_set_object_terms/