4

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.

2
  • Manually i believe May 26, 2011 at 3:16
  • try explaining the use case better
    – Bainternet
    May 26, 2011 at 5:54

3 Answers 3

4

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)

2
  • Sounds good, perhaps a delete hook could delete the taxonomy item? May 26, 2011 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, 2011 at 9:40
1

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

0

I adapted the code from MZAweb and codeprokanner and added lots more consistency checking to provide strict one-to-one relationships between custom posts and custom taxonomy terms. See this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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