3

I have a custom post I am looking to categorize via a custom taxonomy. The taxonomy itself I want to be dependent on the items of another custom post type. Is it possible to populate a taxonomy via the items of a custom post type, or is it something I have to do manually?

Plugins, snippets, guidance on alternat methods of approach would be greatly appreciated.

EDIT WITH EXAMPLE:

I have a custom post type that basically acts like a page. When I create one, I want it to populate a custom taxonomy with its title. Daniel Dvorkin's answer is the sort of solution I was thinking about.

  • Manually i believe – xLRDxREVENGEx May 26 '11 at 3:16
  • try explaining the use case better – Bainternet May 26 '11 at 5:54
3

I always use something like:

add_action('save_post', 'mdz_correlate_casos_taxonomy');
function mdz_correlate_casos_taxonomy( $post_id ){

    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
        return $post_id;

    if ( 'YOUR CUSTOM POST TYPE' == $_POST['post_type'] ){
        if (!wp_is_post_revision($post_id)){
            if (!term_exists( $_POST["post_title"], 'YOUR CUSTOM TAXONOMY' )){

                $termid = wp_insert_term( $_POST["post_title"], 'YOUR CUSTOM TAXONOMY' );

            }
        }
    }

}

But this is prone to get inconsistent (ie: if you delete a post, the term won't get deleted)

  • Sounds good, perhaps a delete hook could delete the taxonomy item? – Levi McCallum May 26 '11 at 8:06
  • Yes, and then you should add code for the case that a taxonomy is added directly, or deleted, etc – MZAweb May 26 '11 at 9:40
0

To follow up on @MZAweb's answer. You can also delete the term automatically like so:

add_action( 'before_delete_post', 'cpk_delete_term' );
function cpk_delete_term( $post_id ) {

  $post = get_post( $post_id );

  if ( term_exists( $post->post_title, 'YOUR_TAXONOMY_NAME' ) ) {
    $term = get_term_by( 'name', $post->post_title, 'YOUR_TAXONOMY_NAME' );
    wp_delete_term( $term->term_id, 'YOUR_TAXONOMY_NAME' );
  }

}

Note we are not doing a check for the post type here because that isn't in the post object when trying to get that info (for whatever reason).

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.