When we create a node programmatically by utilizing drupal node_save() api, we expected that the taxonomy id is saved also by node_save().

It can be achieved if we pass the right information to the $node before invoking the node_save() api.

One can better understand the way $node stores the taxonomy terms data by analyzing the structure of $node->taxonomy.

Below is the result of var_dump of $node and trimmed to just the $node->taxonomy part.


    [taxonomy] => Array
        (
            [254] => stdClass Object 

                (
                    [tid] => 254
                    [vid] => 2
                    [name] => Campervans & Caravans
                    [description] => 
                    [weight] => 0
                )

            [66] => stdClass Object
                (
                    [tid] => 66
                    [vid] => 4
                    [name] => Denmark
                    [description] => 
                    [weight] => 0
                )

        )

After analyzing the array above, you can actually build the array manually or utilizing drupal api taxonomy_get_term($tid) to build the taxonomy object.

To build the taxonomy object :

// example : our taxonomy id (tid) number is 66
$node->taxonomy[66] = taxonomy_get_term(66);

// if we have another taxonomy ? for example the taxonomy id number is 254

$node->taxonomy[254] = taxonomy_get_term(254);

// after this we can safely call the node_save() to save our node

by utilizing the code above, your node taxonomy array object is going to be coded automatically by drupal node_save().