Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress | Make Default taxonomy term(s) for Custom Post Type
<?php
/**
* Add an automatic default custom taxonomy for custom post type.
* If no taxonomy term is selected during post creation, the custom post will be assigned the specififed taxonomy terms during save.
* Just change the 'your-cpt-type' to your custom post type name
* and change 'fruit_tags' and 'soda_flavors' to the taxonomy slug(s) you want to target
* and change 'apple' and 'banana' and 'cola' with the slug(s) of the term(s) you want to make default
* you can add multiple taxonomy at once so the 'soda_flavors' line is applicable only then
*/
function fs_set_default_object_terms( $post_id, $post ) {
if ( 'publish' === $post->post_status && $post->post_type === 'your-cpt-type' ) {
$defaults = array(
'fruit_tags' => array( 'apple', 'banana' ),
'soda_flavors' => array( 'cola' ),
);
$taxonomies = get_object_taxonomies( $post->post_type );
foreach ( (array) $taxonomies as $taxonomy ) {
$terms = wp_get_post_terms( $post_id, $taxonomy );
if ( empty( $terms ) && array_key_exists( $taxonomy, $defaults ) ) {
wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
}
}
}
}
add_action( 'save_post', 'fs_set_default_object_terms', 100, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment