Connecting a taxonomy with a post type

The setup:

  • custom post type of ‘attorney’
  • custom taxonomy of ‘specialty’, which is registered against the ‘attorney’ post type
  • custom post type of ‘practice-area’

For every specialty, there is a matching practice area. However, there are many more practice areas than there are specialties.

Ideally, when viewing a practice area (say, Bankruptcy), I’d be able to list attorneys who have Bankruptcy as a specialty.

I know I could use the posts2posts plugin, and create a connection between the attorney post type and the practice-area post type. However, that would mean essentially setting an attorney’s specialty twice (once as a taxonomy term, and once as a posts2posts connection). Is there a way to somehow make a connection between the a specialty taxonomy term and the relevant practice-area post type? I could simply assume that names and/or slugs will match up, but that’s a pretty hacky/fragile solution.

I’d ideally like to connect regular ‘category’ terms to the various ‘practice-area’ post types as well, to list relevant blog posts on the individual practice area pages (and vice versa).

Suggestions?

2 Answers
2

I’ve dealt a similar requirement and so far the best way to do that is by using a custom field to save the related term id.

That means for each ‘practice-area’ post type, there will be a ‘specialty-term-id’ custom field with the ‘specialty’ term id as value.

Here the action hook to create the term for each post

add_action( 'save_post', 'update_related_term');
function update_related_term($post_id) {
$post_type_as_taxonomy = array('practice-area');
$post = get_post( $post_id );
if(in_array($post->post_type, $post_type_as_taxonomy) && $post->post_status=='publish'){
    $term_args['name'] = $post->post_title;
    $term_args['slug'] = $post->post_name.'';
    $term_id = get_post_meta($post_id, $post->post_type.'-term-id', true);
    if($term_id){
        $term = wp_update_term( $term_id, $post->post_type.'-term', $term_args );
    } else {
        $term = wp_insert_term( $term_args['name'], $post->post_type.'-term', $term_args );
        $meta_status = add_post_meta($post_id, $post->post_type.'-term-id', $term['term_id'], true);
    }

}
}

and the action to delete the term on each post delete

add_action('admin_init', 'codex_init');
function codex_init() {
if (current_user_can('delete_posts')){
    add_action('before_delete_post', 'delete_related_term', 10);
}
}
function delete_related_term($post_id) {
$post_type_as_taxonomy = array('practice-area');
$post = get_post( $post_id );
if (in_array($post->post_type, $post_type_as_taxonomy)) {
    $term = get_post_meta($post_id, $post->post_type.'-term-id', true);
    wp_delete_term( $term, $post->post_type.'-term');
}
}

Note that i used ‘practice-area’ as the custom post type and ‘practice-area-term’ as the related taxonomy.

Hope this help

Leave a Comment