WooCommerce coupon limit quantity by item

For the Dorchester Literary Festival website, I used The Events Calendar plugin together with Events Tickets Plus which allows ticket purchasing through WooCommerce. Festival Friends qualify for a 10% discount on ticket purchases. There is a limit to the number of tickets the deal can be applied to per event. Out of the box, no coupon in WooCommerce allows this so I used the following code to achieve it.

Firstly, we need a place to set the limit per ticket:

 *  Add a custom field to Admin coupon settings pages
function add_coupon_text_field() {

	woocommerce_wp_text_input( array(
        'id'                => 'ff_coupons',
		'class'				=> 'short wc_input_decimal',
        'label'             => __( 'Item limit', 'woocommerce' ),
        'placeholder'       => '',
        'description'       => __( 'Limit quantity per item', 'woocommerce' ),
        'desc_tip'    => true,

    ) );
add_action( 'woocommerce_coupon_options_usage_restriction', 'add_coupon_text_field', 10 );

// Save the custom field value from Admin coupon settings pages
function save_coupon_text_field( $post_id, $coupon ) {

	if( isset( $_POST['ff_coupons'] ) ) {
        $coupon->update_meta_data( 'ff_coupons', sanitize_text_field( $_POST['ff_coupons'] ) );
add_action( 'woocommerce_coupon_options_save', 'save_coupon_text_field', 10, 2 );

Once we’ve got somewhere to enter our limit, we can then use it to validate our coupon:

 * Limit WooCommerce coupon discount to X items per product.
function limit_coupon_discount_per_product( $valid, $coupon, $discount ) {

	$limit = $coupon->get_meta( 'ff_coupons' );

	// Check if the coupon is valid and has a limit.
	if ( $valid && isset ($limit ) && $limit > 0 ) {

		// Get the cart items.
		$cart_items = WC()->cart->get_cart();
		// Loop through the cart items to check the quantity of products.
		foreach ( $cart_items as $cart_item_key => $cart_item ) {

			// Get the quantity of the cart item.
			$quantity = $cart_item['quantity'];
			// Check if the quantity exceeds the limit per coupon.
			if ( $quantity > $limit ) {

				// Adjust the quantity to the limit per coupon.
				WC()->cart->set_quantity( $cart_item_key, $limit );

				// Recalculate the cart totals.
				// Display an error message informing the customer about the quantity limit.
				wc_add_notice(__('Coupon discount is limited to ' . $limit . ' items per product. Excess quantity has been adjusted.', 'woocommerce'), 'error');
    return $valid;
add_filter( 'woocommerce_coupon_is_valid', 'limit_coupon_discount_per_product', 10, 3 );

This code will reset the number of tickets to the limit allowed by the coupon. I’m unsure if it would be better to allow the purchase of the required quantity and only apply the discount to the first ten tickets. If I decide to do this, I will post the code below.