Setting an automatic default taxonomy for a custom post type

1 minute read

By default, a post in WordPress will be assigned to “uncategorized”. If we use a custom taxonomy, say “story” for a “comic” custom post type, there is no default category to fall within anymore.

No taxonomy set

Since there is no default taxonomy to pass through, the post will return Undefined offset: 0 and Trying to get property of non-object errors if WP_debug is 'true'.

Undefined offset error

To fix this, we can use the wp_set_object_terms function:

“(it) Relates an object (post, link etc) to a term and taxonomy type (tag, category, etc). Creates the term and taxonomy relationship if it doesn’t already exist.”

Now we need to add a default taxonomy for this custom post type, so that if no story (taxonomy) is set, the comic post won’t return errors. Let’s assign all comic posts to “draft” by default.

In functions.php ->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Add an automatic default custom taxonomy for custom post type.
* If no story (taxonomy) is set, the comic post will be sorted as “draft” and won’t return an offset error.
*
*/
    function set_default_object_terms( $post_id, $post ) {
        if ( 'publish' === $post->post_status && $post->post_type === 'comic' ) {
            $defaults = array(
                'story' => array( 'draft' )
                );
            $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', 'set_default_object_terms', 0, 2 );

Result:

Now any uncategorised comic post will automatically be sorted as a story “draft” without error. The URL will read as http://url/taxonomy/name.

A post with no taxonomy term checked
The comic post, categorised as a draft.

If we go back to the comic administration panel, we see that “draft” is checked.

The comic post, categorised as a draft.

Know a better way or another method? Please leave a comment below.

Function Reference: wp_set_object_terms

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...