Custom Post Types – Titles as Taxonomies

I’ve written a couple of posts that can help you in this, I’m still writing the explanation to the final piece of this, but here we go.

First, an explanation on how to set up the post types:
this you may not need…

http://drewgourley.com/custom-post-types-for-wordpress/

Second, an explanation on setting up the taxonomies:
pay attention to the point here about capabilites!

http://drewgourley.com/extend-post-types-with-custom-taxonomies/

And finally, wrapping it all up:
this one’s a doosey.

<?php
function associate_posts_register_terms() {
    $args = array('post_type' => '[your type name]', 'numberposts', -1);
    $posts = get_posts($args);
    $lockdown_posts = array();
    foreach ( $posts as $post ) {
        $lockdown_posts[$post->post_name] = $post->post_title;
        if ( get_term_by('slug', $post->post_name, 'post') == false ) {
            $insert = array('slug' => $post->post_name);
            wp_insert_term( $post->post_title, 'post', $insert );
        }
    }
    $posts = get_terms('[your taxonomy name]', array('get' => 'all') );
    foreach ( $posts as $post ) {
        if ( $lockdown_posts[$post->slug] == '') {
            wp_delete_term($post->term_id, 'post');
        } elseif ( $post->name !== $lockdown_posts[$post->slug] ) {
            $update = array('name' => $lockdown_posts[$post->slug], 'slug' => $post->slug);
            wp_update_term($post->term_id, 'post', $update);
        }
    }
}
add_action( 'init', 'associate_posts_register_terms', 2);
?>

After all that is set up appropriately, this function creates taxonomies based on posts which you can use to associate posts back and forth with one another. You’ll have to modify it accordingly to suit your needs, of course, but this should get you going. If you need an explanation on how this works exactly, I can supply it, but it should work pretty easily if you just input the correct things into the bracketed areas in the code there.

Leave a Comment