I have a WooCommerce setup and when I create a new product, I assign the product a category as normal.
Clothing
- Womens
-- Accessories
- Mens
-- Accessories <-- assigned to this term
What I am trying to achieve:
When I choose a child category, I want to also set that post to every parent category direclty above it. In this case, that would look like:
Clothing <-- assigned to this term
- Womens
-- Accessories
- Mens <-- assigned to this term
-- Accessories <-- assigned to this term
Note: Most of my products are created from the front-end by other users, so I can't just select the other boxes, I know that is an option.
My attempt so far:
function set_product_parent_categories( $post_id ) {
$term_ids = wp_get_post_terms( $post_id, 'product_cat' );
foreach( $term_ids as $term_id ) {
if( $term_id->parent > 0 ) {
// Assign product to the parent category too.
wp_set_object_terms( $post_id, $term_id->parent, 'product_cat' );
}
}
}
add_action( 'woocommerce_update_product', __NAMESPACE__.'\\set_product_parent_categories', 10, 1 );