add a category to all products that already have a common category

Solution:

Make backup before using. Change $taxonomy , $post_type , $filter_term_id , $target_term_id with your params.

add_action('init','update_post_taxonomy_terms');
function update_post_taxonomy_terms() {

    $taxonomy = 'product_cat'; // Taxonomy we are looking for
    $post_type = 'product'; // Post type we are looking for
    $filter_term_id = 199; // The taxonomy term id we are looking for 
    $target_term_id = 263; // Term id we want to add

    $args = array(
        'post_type' => $post_type,
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'field' => 'term_id',
                'terms' => $filter_term_id
            )
        )
    );

    $results = new WP_Query($args); // We need all posts that we will update
    $post_ids = wp_list_pluck( $results->posts, 'ID' ); // We need only post ids
    
    error_log(print_r($post_ids,true)); // Check the post ids that will be updated if all good uncomment rest of the code

    //Uncomment when ready
    // foreach($post_ids as $post_id):
    //     wp_set_post_terms( $post_id, $target_term_id, $taxonomy );
    // endforeach;
}