How can I set taxonomy programmatically

Here is my situation. I plan to distribute a theme I am working on and it has a custom post type called Code and it has a custom taxonomy called Languages now I also use a custom metabox with a dropdown list of available languages, I need to somehow make the value that they choose in the select dropdown box to not only save as the meta value (which it does already) but I need that value to also be picked as the taxonomy for that post

So If they make a post and pick the Language “PHP” in the meta_box, then when they post, it will make the “PHP” taxonomy be selected. I plan to hide the taxonomy UI and auto populate all the possible taxonomy terms

Read More

1) How can I make a metabox value be saved in addition to a meta_value but also as the taxonomy for that post?

Update

Ok I have found a possible solution,wp_set_object_terms( 123, 'PHP', 'tag' ); will add a PHP tag taxonomy to post ID 123.

So I just need to know how to get a post ID when it is being posted, is that even possible as the post is not in the DB yet on a new post? Any ideas

Related posts

Leave a Reply

1 comment

  1. You should hook your actions to the save_post hook. It fires right after the post is created and the $post_id and other $post data variables are already available.

    Something like this should do the trick:

    add_action( 'save_post', 'jason_code_save_post', 10, 2 );
    
    function jason_code_save_post( $post_ID, $post ) {
    
         if ( 'code' != $post->post_type || wp_is_post_revision( $post_ID ) )
              return;
    
         wp_set_object_terms( $post_ID, 'PHP', 'tag' );
    
    }
    

    See Plugin_API/Action_Reference/save_post.

    Let me know if something needs more explanation…