Will McLean is a designer and artist working in the Central Coast of NSW where he lives with his wife and 2 children.

Will draws and paints out of habit and addiction. He writes about his struggles on the battlefield of art in the Art Archive section of this site.

Will is a meticulous developer and favours simplicity and clarity within his code. He can’t stand writing things twice so searches for any way to automate. His experiments can be found in the Exercises section of this site.

Will designs within systems. No project is too small for a design system. He favours the unusual, if not, how can he progress? You can read about his work in the Case Studies section of this site.

Updated: October 8, 2018

This is a Knowledge Base post.

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

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 );