Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyspiansky/d6bab61e26284721593f22e15c003476 to your computer and use it in GitHub Desktop.
Save vyspiansky/d6bab61e26284721593f22e15c003476 to your computer and use it in GitHub Desktop.
WordPress: how to set a default category for a custom post type
<?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