Will McLean
Process diary

Create a matching term in a taxonomy when publishing a custom post

Last modified: October 8, 2018
Created: February 16, 2018

Recently I built a site that needed to have terms that matched the name of every custom post type ‘brand’ so that other posts could be grouped under those brands. Rather than do this manually which is incredibly boring and leaves a lot of room for human error I wrote a few functions to automate it. The task was to:
– Create a term that matches the custom post title when a post is published
– Remove that term when the post is deleted or unpublished

To do this I hooked into the transition_post_status action, tested if the $new_status was ‘publish’ or not and then added or removed the term based on that result.

You need to register both a custom post type and a taxonomy to make this work. You can do so by consulting the WordPress codex.

function add_term( $post ) {
    // Add term
    $term_slug = $post->post_name;
    if ( !term_exists( $term_slug, 'brand' ) ):
        wp_insert_term( $post->post_title, 'brand', $args = array( 'slug' => $term_slug ) );
    endif;
    // Add post to term
    wp_set_object_terms( $post->ID, array( $term_slug ), 'brand', true );
}

function remove_term( $post ) {
    $term_slug = $post->post_name;
    $term = get_term_by( 'slug', $term_slug, 'brand' );
    if ( term_exists( $term_slug, 'brand' ) ):
        wp_delete_term( $term->term_id, 'brand' );
    endif;
}

function toggle_term( $new_status, $old_status, $post ) {
    if ( $new_status == 'publish' ) {
        add_term( $post );
    } else {
        remove_term( $post );
    }
}

add_action( 'transition_post_status', 'toggle_term', 10, 3 );

This is a Knowledge Base post.