Try this, I have updated it with a hook for when you save the product, try saving a product and see if it assigns everything correctly
add_action('save_post_product', 'wpb_assign_product_to_categories_on_save');
function wpb_assign_product_to_categories_on_save($post_id) {
// Check if this is a valid call
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
// Check the user's permissions
if (!current_user_can('edit_post', $post_id))
return;
// Call the function to assign product to categories
wpb_assign_product_to_matching_category($post_id);
}
function wpb_assign_product_to_matching_category($post_id) {
// Retrieve the custom id for this product
$product_custom_id = get_post_meta($post_id, 'custom_id', true);
if (!empty($product_custom_id)) {
$categories = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
));
$matching_category_ids = array();
foreach ($categories as $category) {
// Retrieve the custom id for this category
$category_custom_id = get_term_meta($category->term_id, 'custom_id', true);
// Check if the product's custom id matches the category's custom id
if ($product_custom_id === $category_custom_id) {
$matching_category_ids[] = $category->term_id;
}
}
// Assign the product to the matching categories
if (!empty($matching_category_ids)) {
wp_set_post_terms($post_id, $matching_category_ids, 'product_cat');
}
}
}