Skip to content

Instantly share code, notes, and snippets.

@nathaningram
Created May 10, 2022 21:50
Show Gist options
  • Save nathaningram/d90ad11fc6a2d3b43ab4f1d22e515b3a to your computer and use it in GitHub Desktop.
Save nathaningram/d90ad11fc6a2d3b43ab4f1d22e515b3a to your computer and use it in GitHub Desktop.
Set a Default Taxonomy for CPTs
// Set "Upcoming" as Default Tax for Events (this applies on publish)
// Source: https://gist.github.com/mayeenulislam/f208b4fd408fd4742c06
function ni_set_default_object_terms( $post_id, $post ) {
if ( 'publish' === $post->post_status ) {
$defaults = array(
'post_tag' => array( 'event' ),
'event-status' => array( 'upcoming' ),
);
$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', 'bni_set_default_object_terms', 100, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment