Forked from mayeenulislam/Default Taxonomy Term for CPT
Last active
September 14, 2017 12:32
-
-
Save Garconis/0641a39ce10c4f56e5d741e9e0fd97e9 to your computer and use it in GitHub Desktop.
WordPress | Make Default taxonomy term(s) for Custom Post Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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