Back to Tips & Tricks

WooCommerce Checkout Attendee Name for Each Ticket, Saved to a CCT

BoostMyCroco TeamPublished on
Event tickets each linked to its own guest card in a database: one attendee name per ticket at WooCommerce checkout

To collect an attendee name for each ticket at the WooCommerce checkout, use the classic checkout. Loop over the cart and print one required text field for every unit of each ticket product, so three tickets give three name fields. Validate the names, store them on the order with the HPOS-safe order API, and create one JetEngine Custom Content Type (CCT) item per guest only when the order reaches a paid status.

The snippet below does all of this without a checkout plugin. It needs the classic (shortcode) checkout, not the Checkout block.

What you're building

  • One required name field for every ticket unit in the cart. Other products get no fields.
  • WooCommerce refuses the order if any name is empty or too long.
  • The names are stored on the order and shown in the admin, on the customer's order pages and in order emails.
  • When the order becomes processing or completed, each guest becomes its own CCT item with its own ID, the order ID, product ID, ticket number and buyer email, ready to list, filter and export.

The CCT items wait for payment on purpose: abandoned checkouts and failed payments would otherwise leave guest records nobody paid for. A flag on the order stops a second run when it moves from processing to completed.

Step 1: check which checkout you have (block vs classic)

Many newer stores use the Checkout block. It is rendered by React from the Store API, so classic hooks like woocommerce_after_checkout_billing_form never run there. That is why most "add a field" snippets do nothing on those stores, as this write-up on custom checkout fields explains.

The block checkout's Additional Checkout Fields API registers fixed fields in the contact, address or order location, with no option to repeat a field per cart quantity. Checkout Field Editor's free version can't repeat fields by quantity either, and its Pro repeat rules work only in the classic checkout.

  1. Open the page WooCommerce uses as the Checkout page in the editor.
  2. If you see a Checkout block, remove it and add a Shortcode block containing [woocommerce_checkout].
  3. Save, then confirm in your WooCommerce page settings that this page is still assigned as the Checkout page.

If you use an Elementor Pro Checkout widget or a JetWooBuilder checkout template, test on your template. The fields only appear if it fires the classic billing form hooks.

Step 2: create the Attendees CCT to save WooCommerce checkout fields

  1. Go to JetEngine > JetEngine > Modules > Default Modules and turn on Custom Content Types.
  2. Go to JetEngine > Custom Content Types > Add New.
  3. Set the Name to Attendees and the Slug to attendees. The DB Table Name fills in as wp_jet_cct_attendees on sites with the default wp_ database prefix; otherwise it is {your DB prefix}jet_cct_attendees.
  4. Add the fields below. The Name/ID is what the snippet writes to, so type it exactly as shown.
  5. Turn on Show in the admin columns for the fields you want in the list. For the number fields, also turn on Is sortable and Is numeric field.
Field Name/IDTypeAdmin column
attendee_nameTextYes
order_idNumberYes, sortable, numeric
product_idNumberYes, sortable, numeric
ticket_numberNumberYes
buyer_emailTextYes
ticket_statusTextYes (the snippet sets it to active)

The CCT overview in the Crocoblock knowledge base covers every setting. For another worked example, see our JetEngine review system built on a CCT.

Step 3: mark ticket products with a category

Go to Products > Categories and create a category with the slug tickets. Assign it to every product that needs guest names. For variable products, assign it to the parent product; the snippet checks the parent, so all variations get fields.

The check uses has_term(), which doesn't match products assigned only to a child category of tickets. Tick tickets itself on those products too.

Step 4: repeat a WooCommerce checkout field based on quantity and save it to a JetEngine CCT

This is order data, so keep it out of the theme, where a theme switch would stop it. Use one of these places:

  • Must-use plugin: create wp-content/mu-plugins/bmc-ticket-attendees.php (create the mu-plugins folder if needed) and paste the whole snippet.
  • Code Snippets plugin: paste everything after the opening <?php line and set the snippet to run everywhere.

Change the four settings at the top if they differ on your site: cct_slug, ticket_cat (the category slug), max_length (the longest name allowed) and paid_statuses (the order statuses that mean paid):

Code

<?php
/**
 * Plugin Name: BMC Ticket Attendees to JetEngine CCT
 * Description: One guest-name field per ticket on the classic WooCommerce checkout. Each guest becomes a JetEngine CCT item once the order is paid.
 */

defined( 'ABSPATH' ) || exit;

/* ---------- Settings ---------- */

function bmc_att_settings() {
	return array(
		'cct_slug'      => 'attendees',                        // JetEngine CCT slug.
		'ticket_cat'    => 'tickets',                          // Product category slug for ticket products.
		'max_length'    => 100,                                // Max characters per guest name.
		'paid_statuses' => array( 'processing', 'completed' ), // Order statuses that mean paid.
	);
}

/* ---------- Helpers ---------- */

// Ticket lines in the cart. Checks the parent product, so variable tickets work too.
function bmc_att_ticket_lines() {
	$lines = array();
	if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
		return $lines;
	}
	$settings = bmc_att_settings();
	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		if ( has_term( $settings['ticket_cat'], 'product_cat', (int) $cart_item['product_id'] ) ) {
			$lines[ $cart_item_key ] = $cart_item;
		}
	}
	return $lines;
}

// Flat field key, also used as the HTML id: bmc_attendee_{cart item key}_{ticket number}.
function bmc_att_field_key( $cart_item_key, $number ) {
	return 'bmc_attendee_' . sanitize_key( $cart_item_key ) . '_' . absint( $number );
}

// Read one posted name safely. WooCommerce checks its own checkout nonce before these hooks run.
function bmc_att_posted_name( $key ) {
	// phpcs:ignore WordPress.Security.NonceVerification.Missing
	if ( ! isset( $_POST[ $key ] ) || ! is_string( $_POST[ $key ] ) ) {
		return '';
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Missing
	return sanitize_text_field( wp_unslash( $_POST[ $key ] ) );
}

function bmc_att_product_name( $cart_item ) {
	return wp_strip_all_tags( $cart_item['data']->get_name() );
}

// JetEngine CCT item handler, or null when the module or the CCT is missing.
function bmc_att_cct_handler() {
	if ( ! function_exists( 'jet_engine' ) || ! jet_engine()->modules->is_module_active( 'custom-content-types' ) ) {
		return null;
	}
	$settings = bmc_att_settings();
	$type     = \Jet_Engine\Modules\Custom_Content_Types\Module::instance()->manager->get_content_types( $settings['cct_slug'] );
	return $type ? $type->get_item_handler() : null;
}

/* ---------- (a) Show one name field per ticket ---------- */

add_action( 'woocommerce_after_checkout_billing_form', 'bmc_att_render_fields' );
function bmc_att_render_fields( $checkout ) {
	$lines = bmc_att_ticket_lines();
	if ( empty( $lines ) ) {
		return;
	}
	$settings = bmc_att_settings();
	echo '<div class="bmc-attendees"><h3>' . esc_html__( 'Guest names', 'bmc' ) . '</h3>';
	foreach ( $lines as $cart_item_key => $cart_item ) {
		$qty = (int) $cart_item['quantity'];
		for ( $i = 1; $i <= $qty; $i++ ) {
			$key = bmc_att_field_key( $cart_item_key, $i );
			woocommerce_form_field(
				$key,
				array(
					'type'      => 'text',
					'label'     => sprintf( 'Ticket %1$d – %2$s: guest name', $i, esc_html( bmc_att_product_name( $cart_item ) ) ),
					'required'  => true,
					'maxlength' => $settings['max_length'],
					'class'     => array( 'form-row-wide' ),
				),
				$checkout->get_value( $key )
			);
		}
	}
	echo '</div>';
}

/* ---------- (b) Check the names ---------- */

add_action( 'woocommerce_after_checkout_validation', 'bmc_att_validate', 10, 2 );
function bmc_att_validate( $data, $errors ) {
	$settings = bmc_att_settings();
	foreach ( bmc_att_ticket_lines() as $cart_item_key => $cart_item ) {
		$product_name = esc_html( bmc_att_product_name( $cart_item ) );
		$qty          = (int) $cart_item['quantity'];
		for ( $i = 1; $i <= $qty; $i++ ) {
			$name = bmc_att_posted_name( bmc_att_field_key( $cart_item_key, $i ) );
			if ( '' === $name ) {
				$errors->add( 'bmc_attendee_missing', sprintf( 'Please enter the guest name for ticket %1$d of %2$s.', $i, $product_name ) );
			} elseif ( mb_strlen( $name ) > $settings['max_length'] ) {
				$errors->add( 'bmc_attendee_too_long', sprintf( 'The guest name for ticket %1$d of %2$s is longer than %3$d characters.', $i, $product_name, $settings['max_length'] ) );
			}
		}
	}
}

/* ---------- (c) Save the names on the order (HPOS-safe) ---------- */

add_action( 'woocommerce_checkout_create_order', 'bmc_att_save_to_order', 10, 2 );
function bmc_att_save_to_order( $order, $data ) {
	$list = array();
	foreach ( bmc_att_ticket_lines() as $cart_item_key => $cart_item ) {
		$qty = (int) $cart_item['quantity'];
		for ( $i = 1; $i <= $qty; $i++ ) {
			$list[] = array(
				'product_id'    => (int) $cart_item['product_id'],
				'variation_id'  => isset( $cart_item['variation_id'] ) ? (int) $cart_item['variation_id'] : 0,
				'product_name'  => bmc_att_product_name( $cart_item ),
				'ticket_number' => $i,
				'name'          => bmc_att_posted_name( bmc_att_field_key( $cart_item_key, $i ) ),
			);
		}
	}
	if ( $list ) {
		// WooCommerce saves the order right after this hook, so no save() is needed here.
		$order->update_meta_data( '_bmc_attendees', $list );
	}
}

/* ---------- (d) Create one CCT item per guest once the order is paid ---------- */

foreach ( bmc_att_settings()['paid_statuses'] as $bmc_status ) {
	add_action( 'woocommerce_order_status_' . $bmc_status, 'bmc_att_create_cct_items', 20, 1 );
}

function bmc_att_create_cct_items( $order_id ) {
	$order = wc_get_order( $order_id );
	if ( ! $order || 'yes' === $order->get_meta( '_bmc_attendees_created' ) ) {
		return; // No order, or already done (stops duplicates on processing -> completed).
	}
	$attendees = $order->get_meta( '_bmc_attendees' );
	if ( empty( $attendees ) || ! is_array( $attendees ) ) {
		return;
	}
	$handler = bmc_att_cct_handler();
	if ( ! $handler ) {
		$order->add_order_note( 'Attendee records not created: JetEngine CCT module or CCT not found.' );
		return;
	}
	// CCT item IDs keyed by guest position. Guests saved in an earlier run are skipped.
	$ids = $order->get_meta( '_bmc_attendee_cct_ids' );
	if ( ! is_array( $ids ) ) {
		$ids = array();
	}
	$created = 0;
	$skipped = 0;
	foreach ( $attendees as $index => $attendee ) {
		if ( ! empty( $ids[ $index ] ) ) {
			continue;
		}
		$name = isset( $attendee['name'] ) ? trim( (string) $attendee['name'] ) : '';
		if ( '' === $name ) {
			// Orders that bypass the checkout form (e.g. express payment buttons) have no names. Skip them.
			$skipped++;
			continue;
		}
		// Array keys must match the CCT field Name/IDs exactly.
		$item_id = $handler->update_item(
			array(
				'attendee_name' => $name,
				'order_id'      => $order->get_id(),
				'product_id'    => $attendee['product_id'],
				'ticket_number' => $attendee['ticket_number'],
				'buyer_email'   => $order->get_billing_email(),
				'ticket_status' => 'active',
				'cct_status'    => 'publish',
				'cct_author_id' => $order->get_customer_id(),
			)
		);
		if ( is_wp_error( $item_id ) ) {
			$order->add_order_note( sprintf( 'Attendee record failed for ticket %1$d of %2$s: %3$s', absint( $attendee['ticket_number'] ), $attendee['product_name'], $item_id->get_error_message() ) );
		} elseif ( $item_id ) {
			$ids[ $index ] = (int) $item_id;
			$created++;
		} else {
			$order->add_order_note( sprintf( 'Attendee record failed for ticket %1$d of %2$s.', absint( $attendee['ticket_number'] ), $attendee['product_name'] ) );
		}
	}
	$order->update_meta_data( '_bmc_attendee_cct_ids', $ids );
	if ( count( $ids ) + $skipped === count( $attendees ) ) {
		// Flag only when every named guest has a record, so failed inserts are retried on the next paid status.
		$order->update_meta_data( '_bmc_attendees_created', 'yes' );
	}
	$order->save();
	$order->add_order_note( sprintf( 'Attendee records: %1$d created in this run, %2$d of %3$d saved in total, %4$d skipped (no guest name).', $created, count( $ids ), count( $attendees ), $skipped ) );
}

/* ---------- Show guests: order screen, thank-you page, My Account order view ---------- */

add_action( 'woocommerce_admin_order_data_after_billing_address', 'bmc_att_print_list' );
add_action( 'woocommerce_order_details_after_order_table', 'bmc_att_print_list' );
function bmc_att_print_list( $order ) {
	if ( ! is_a( $order, 'WC_Order' ) ) {
		return;
	}
	$attendees = $order->get_meta( '_bmc_attendees' );
	if ( empty( $attendees ) || ! is_array( $attendees ) ) {
		return;
	}
	echo '<h3>' . esc_html__( 'Guests', 'bmc' ) . '</h3><ul class="bmc-attendee-list">';
	foreach ( $attendees as $attendee ) {
		printf(
			'<li>%1$s – ticket %2$d: <strong>%3$s</strong></li>',
			esc_html( $attendee['product_name'] ),
			absint( $attendee['ticket_number'] ),
			esc_html( $attendee['name'] )
		);
	}
	echo '</ul>';
}

/* ---------- Show guests in order emails that print order meta ---------- */

add_filter( 'woocommerce_email_order_meta_fields', 'bmc_att_email_fields', 10, 3 );
function bmc_att_email_fields( $fields, $sent_to_admin, $order ) {
	if ( ! is_a( $order, 'WC_Order' ) ) {
		return $fields;
	}
	$attendees = $order->get_meta( '_bmc_attendees' );
	if ( empty( $attendees ) || ! is_array( $attendees ) ) {
		return $fields;
	}
	// Names were cleaned with sanitize_text_field() at checkout, so no HTML is stored.
	// Raw text keeps characters like & readable in plain-text emails.
	$fields['bmc_attendees'] = array(
		'label' => __( 'Guests', 'bmc' ),
		'value' => implode( ', ', wp_list_pluck( $attendees, 'name' ) ),
	);
	return $fields;
}

How the snippet works

(a)–(c): bmc_att_render_fields() prints one field per ticket unit with a flat key (no brackets, because the key is also the HTML id). Validation reads $_POST through a guarded, sanitized helper, because these fields are not in the $data array. woocommerce_checkout_create_order then stores the list with $order->update_meta_data(), which works with or without HPOS.

(d): On woocommerce_order_status_processing and _completed, the code gets the CCT through Module::instance()->manager->get_content_types() and calls update_item() on its handler without an _ID, which creates an item and returns its ID, as shown in Crocoblock's JetEngine CCT CRUD gist. Every new item gets ticket_status = active.

Failed inserts are logged in the order notes per ticket. IDs are stored per guest, and the _bmc_attendees_created flag is set only when every named guest has a record. After fixing a failure, move the order into another paid status (for example processing to completed) and only the missing guests are created. Tickets with no name, which can happen with payment buttons that skip the checkout form, are skipped and counted in the note so you can add them by hand.

If you take bank transfers or other manual payments, check which status those orders get once marked paid, and add it to paid_statuses if needed.

Step 5: guest names on the order screen and in emails

The snippet prints the guest list under the billing address on the order edit screen (legacy and HPOS), on the thank-you page and on the single order view in My Account. The woocommerce_email_order_meta_fields filter adds a "Guests" row to the order emails that print order meta, such as new order, processing, completed and on-hold. Place a test order to see which emails show it in your WooCommerce version.

Test it

  1. Add 2 units of a ticket product and 1 other product to the cart. The checkout should show exactly 2 guest fields.
  2. Leave one empty and place the order. You should see "Please enter the guest name for ticket 2 of …".
  3. Fill both in and pay with a test gateway. The order notes should say "Attendee records: 2 created in this run, 2 of 2 saved in total, 0 skipped (no guest name)."
  4. Open the Attendees CCT. You should see 2 items with the order ID, product ID and ticket_status active.
  5. Mark the order completed. No new items should appear.
  6. Repeat as a logged-out guest and check that items were created and which author they show.
  7. Place one order through your real gateway in sandbox mode, so its callback or webhook marks the order paid with no logged-in user. Check the notes and the CCT list.

Optional: list guests on the front end

In JetEngine > Query Builder, add a query with the Query Type set to Custom Content Type, choose Attendees, and filter by product_id (one event's guests) or order_id (one buyer's tickets). Add a condition where ticket_status equals active so cancelled and refunded tickets drop out. Use the query as the source of a Listing Grid. The Query Builder overview covers the settings; if the grid stays empty, see our common JetEngine Query Builder mistakes.

Optional: cancelled and refunded orders

Mark guest records instead of deleting them, so you keep a history. Paste this at the end of the same file or snippet as the main code, because it uses its helper functions. It sets ticket_status to cancelled or refunded, and back to active if the order is paid again:

foreach ( array( 'cancelled', 'refunded' ) as $bmc_status ) {
	add_action( 'woocommerce_order_status_' . $bmc_status, 'bmc_att_sync_ticket_status', 20, 1 );
}
// Priority 30 runs after bmc_att_create_cct_items and resets records when a cancelled order is paid again.
foreach ( bmc_att_settings()['paid_statuses'] as $bmc_status ) {
	add_action( 'woocommerce_order_status_' . $bmc_status, 'bmc_att_sync_ticket_status', 30, 1 );
}

function bmc_att_sync_ticket_status( $order_id ) {
	$order = wc_get_order( $order_id );
	if ( ! $order ) {
		return;
	}
	$is_paid    = in_array( $order->get_status(), bmc_att_settings()['paid_statuses'], true );
	$new_status = $is_paid ? 'active' : $order->get_status();
	$current    = (string) $order->get_meta( '_bmc_ticket_status' );
	// Paid orders only need a reset when their records were marked before.
	if ( ( $is_paid && '' === $current ) || $new_status === $current ) {
		return;
	}
	$ids     = $order->get_meta( '_bmc_attendee_cct_ids' );
	$handler = bmc_att_cct_handler();
	if ( empty( $ids ) || ! is_array( $ids ) || ! $handler ) {
		return;
	}
	$updated = 0;
	foreach ( $ids as $item_id ) {
		// Passing _ID updates the existing item instead of creating a new one.
		$result = $handler->update_item( array(
			'_ID'           => (int) $item_id,
			'ticket_status' => $new_status,
		) );
		if ( is_wp_error( $result ) ) {
			$order->add_order_note( sprintf( 'Attendee record %1$d not updated: %2$s', (int) $item_id, $result->get_error_message() ) );
		} elseif ( ! $result ) {
			$order->add_order_note( sprintf( 'Attendee record %d not updated.', (int) $item_id ) );
		} else {
			$updated++;
		}
	}
	$order->add_order_note( sprintf( 'Attendee records marked as %1$s: %2$d of %3$d updated.', $new_status, $updated, count( $ids ) ) );
	if ( $updated === count( $ids ) ) {
		$order->update_meta_data( '_bmc_ticket_status', $new_status );
		$order->save();
	}
}

Before the first test, export a backup of the {your DB prefix}jet_cct_attendees table with your database tool. Then test on one order: cancel it, check that the note reports every record updated, and check that the other fields on each item stay unchanged. If they were blanked, restore the backup and don't use this part. If some records failed, the stored status isn't changed, so the next status change retries.

A partial refund doesn't change the order status, so no records are marked; edit that guest's ticket_status in the CCT by hand.

Troubleshooting

  • Guest fields don't appear at checkout. The page uses the Checkout block; replace it with [woocommerce_checkout]. Event plugins hit the same wall, as in this FooEvents report of missing attendee fields. Also check that the product is assigned directly to tickets.
  • Spinner never stops, or "Undefined array key" warnings. Other checkout code reads $_POST without isset() while WP_DEBUG_DISPLAY is on, which breaks the checkout AJAX response. This snippet guards every read.
  • Names empty in $order->get_meta(), exports or the REST API. An older snippet used update_post_meta(), which those don't read on HPOS stores. Use $order->update_meta_data().
  • No CCT items created. Read the order notes. "CCT not found" means the module is off or the slug doesn't match. get_content_types() also returns nothing before init priority 12, so don't move this logic into an earlier hook. If items appear on manual status changes but not when a gateway callback marks the order paid, check whether a permission check blocks inserts with no logged-in user; JetEngine's jet-engine/custom-content-types/user-has-access filter is the place to start.
  • Items created but fields blank. The array keys don't match the CCT field Name/IDs exactly.
  • Each guest created twice. Another snippet or an older copy also creates items. The flag only protects this function.

You now have one field per ticket, names stored safely on the order, and one CCT item per paid guest. If you'd rather have it built and tested on your store, post a request on BoostMyCroco.

Frequently Asked Questions

Can I collect an email or phone number for each attendee too?
Yes. Call woocommerce_form_field() a second time inside the same loop with its own key, such as bmc_attendee_email_ plus the cart item key and ticket number. Validate it the same way, using sanitize_email() and is_email() for emails, add it to the saved array, and create a CCT field with the same Name/ID.
Does this work with the WooCommerce Checkout block?
No. The Checkout block does not run the classic checkout hooks this code relies on. Its Additional Checkout Fields API registers fixed fields in the contact, address or order location and has no option to repeat a field per cart quantity. Use the [woocommerce_checkout] shortcode on your Checkout page.
What happens if the customer changes the ticket quantity after reaching checkout?
The fields are printed when the checkout page loads, so they match the cart at that moment. Validation always counts the current cart, so if the quantity no longer matches, the customer gets an error for the missing name. Reloading the checkout page shows the correct number of fields.
Why were no attendee records created for a bank transfer order?
Records are only created when an order reaches one of the statuses in paid_statuses, which are processing and completed by default. Manual payment orders stay in another status until you confirm payment. Move the order to processing once paid, or add its status to the paid_statuses setting.
How do I export the guest list?
Each guest is a row in the {your DB prefix}jet_cct_attendees table (wp_jet_cct_attendees on sites with the default wp_ prefix), so any database export tool can export it. You can also turn on the Register get/create/update/delete item REST API Endpoint option in the CCT settings and pull items from another system. For an on-site list, use a Query Builder CCT query in a Listing Grid.

This guide answers a question from our community: I need to add custom fields in woocommerce checkout and save them into CCT (JetEngine)

Sources

  1. Add Custom Fields to WooCommerce Checkout - DEV Community (dev.to)
  2. Checkout Field Editor (Checkout Manager) for WooCommerce (wordpress.org)
  3. Custom Content Type (CCT) Overview — JetEngine (crocoblock.com)
  4. JetEngine CCT CRUD · GitHub - Gist (gist.github.com)
  5. Query Builder Overview — JetEngine (crocoblock.com)
  6. Compatibility Issue with the FooEvents For Woocommerce. Attendee fields does not show in the checkout page. #45074 (github.com)
  7. API to interact with JetEngine CCT from directly PHP code · GitHub (gist.github.com)

Related tips