There are two flaws in the code that I can see. The first one is a bug in this code
if($post->post_type != 'product')
If no post exists, you get the following error
Notice: Trying to get property of non-object…
This can be fixed by first checking if a post isset
if(isset($post) && $post->post_type != 'product')
Secondly, wp_set_post_terms()
should not be used for custom taxonomies on custom post types, the correct function should be wp_set_object_terms()
. From the codex page
This function will only work on the native post type. For a taxonomy on a custom post type use
wp_set_object_terms()
So, your code should look something like this
add_action('save_post', 'assign_parent_terms');
function assign_parent_terms($post_id){
global $post;
if(isset($post) && $post->post_type != 'product')
return $post_id;
// get all assigned terms
$terms = wp_get_post_terms($post_id, 'product_cat' );
foreach($terms as $term){
while($term->parent != 0 && !has_term( $term->parent, 'product_cat', $post )){
// move upward until we get to 0 level terms
wp_set_object_terms($post_id, array($term->parent), 'product_cat', true);
$term = get_term($term->parent, 'product_cat');
}
}
}