Created
September 20, 2021 14:19
-
-
Save vyspiansky/d6bab61e26284721593f22e15c003476 to your computer and use it in GitHub Desktop.
WordPress: how to set a default category for a custom post type
This file contains 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_action('save_post', function($post_id, $post) { | |
$custom_post_type = 'custom-post-type'; | |
$custom_taxonomy = 'custom-taxonomy'; | |
$default_term_slug = 'default-term-slug'; | |
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; | |
// If this is just a revision, don't set default category | |
if (wp_is_post_revision($post_ID)) return; | |
if ($post->post_type !== $custom_post_type) return; | |
if (!in_array($post->post_status, ['publish', 'draft'])) return; | |
// Only set default category if no terms are set yet | |
$terms = wp_get_post_terms($post_id, $custom_taxonomy); | |
if (!empty($terms)) return; | |
$default_term = get_term_by('slug', $default_term_slug, $custom_taxonomy); | |
if (empty($default_term)) return; | |
// Assign the default category | |
wp_set_object_terms($post_id, $default_term->term_id, $custom_taxonomy); | |
}, 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment