Programmatically add and remove woocommerce product category

Add the codes below to a custom plugin

To add the category to new products

function set_new_product_cat( $post_id, $post, $update ) {
    if("product" === $post->post_type){
        // Exit out as we are updating an existing product 
        if ( $update ) {
            return;
        }
        
        //Appends the category 35 to the product
        wp_set_post_categories( $post->ID, 35, true);
    }
}
add_action( 'wp_insert_post', 'set_new_product_cat', 10, 3 );

and this for setting up a cron task to once a day check for products older then 30 days that have the category still set and unset it

function remove_new_product_cat_deactivate() {
    wp_clear_scheduled_hook( 'remove_new_product_cat_cron' );
}
 
add_action('init', function() {
    add_action( 'remove_new_product_cat_cron', 'remove_new_product_cat_run_cron' );
    register_deactivation_hook( __FILE__, 'remove_new_product_cat_deactivate' );
 
    if (! wp_next_scheduled ( 'remove_new_product_cat_cron' )) {
        wp_schedule_event( time(), 'daily', 'remove_new_product_cat_cron' );
    }
});
function remove_new_product_cat_run_cron() {
    // Get all products older then 30 days that have the category with id 35
    $args = array(
        'numberposts'      => -1,
        'category'         => 35,
        'post_type'        => 'product',
        'date_query' => array(
            'before' => date('Y-m-d', strtotime('-30 days')) 
        )
    );
    $products = get_posts($args);
    
    // Loop trough the products
    foreach ( $products as $product) {
        // Grab an array of currently set categories
        $cats  = wp_get_post_categories($product);
        
        // Remove 35 from the list
        if (($key = array_search(35, $cats)) !== false) {
            unset($messages[$key]);
        }
        
        // Update the categories overwriting existing ones
        wp_set_post_categories( $post->ID, $cats, false);
    }
}