WordPress default taxonomy (Categories) has the item Uncategorized by default. How to add a default item to a new custom taxonomy?
functions.php:
// === CUSTOM TAXONOMIES === //
function my_custom_taxonomies() {
register_taxonomy(
'block', // internal name = machine-readable taxonomy name
'static_content', // object type = post, page, link, or custom post-type
array(
'hierarchical' => true,
'labels' => array(
'name' => __( 'Blocks' ),
'singular_name' => __( 'Block' ),
'add_new_item' => 'Add New Block',
'edit_item' => 'Edit Block',
'new_item' => 'New Block',
'search_items' => 'Search Block',
'not_found' => 'No Block found',
'not_found_in_trash' => 'No Block found in trash',
),
'query_var' => true, // enable taxonomy-specific querying
'rewrite' => array( 'slug' => 'block' ), // pretty permalinks for your taxonomy?
)
);
}
add_action('init', 'my_custom_taxonomies', 0);
EDIT: I just want to have the taxonomy item there when the theme is installed. It doesn’t have to automatically be added to any empty term.
Have a look here:
https://web.archive.org/web/20150403012347/http://wordpress.mfields.org/2010/set-default-terms-for-your-custom-taxonomies-in-wordpress-3-0/
Basically what you need to do is use the save_post hook to check the terms for the post and add the default term from your taxonomy if it’s empty.
If you just want to have an initial term set in your custom taxonomy, then you can use
wp_insert_term()
. Probably easiest to add it in the same function that you’re using to create your custom taxonomy. As t3ios adds in the comments, you should callget_term()
first, and only insert the term if the return value is null (ie the term doesn’t exist).This example code is from the Codex: http://codex.wordpress.org/Function_Reference/wp_insert_term
Update as of 2020
5.5.0
default_term
argument.Since WordPress version 5.5.0 release, you’re now able to specify a default term when registering a new custom taxonomy using the very handy
default_term
argument.Default category is hardcoded case in
wp_insert_post()
function.So it can’t be replicated exactly, but you can handle it in other ways. I’d try to hook into post status transition for new posts and assign wanted default term if none were assigned during post creation.
I needed to populate a Custom Taxonomy “Days” with the days of the week..I did not want the client to have to mess with creating days, or get in there and delete days or misspell days. Following the above advice I came up with this, but I am wondering if there is a more concise way of coding it:
Using the Default Term plugin you could do this
By default when the post is submitted it will save the default term to the post if there are no term checked. It works for both hierarchical and non hierarchical taxonomies.