Custom Field API

If you’re selling tickets, it’s not uncommon that you’ll need to gather some form of custom information. Do you need your customers to check a box verifying that they’re over 18? Do you need to get a phone number for each event? Find out which meal a customer would prefer for lunch?

My Tickets supports a custom field API that can add a custom field into the “Add to Cart” form. What it does is largely up to you; but it’s very easy to write a basic extension to collect custom data for an event.

Custom fields are added using the filter ‘mt_custom_fields‘.

In the filter, all you need to do is add an array of data to the custom fields array that passes the label for your custom field, a sanitization callback function, a display callback function, an input type, a set of values to choose from, and a context.

Any of these values can be omitted except for the label.

If you only provide a label, you will create a text input field with no default value. It’ll be sanitized using esc_sql and strip_tags. The display callback will call esc_attr and stripslashes on the value for display. When you create a callback, your callback gets two arguments: the data value itself, and the context it’s shown in. That will either by ‘cart’, for the shopping cart or add to cart context, or ‘payment’, if it’s being shown in the admin.

Supported input types include all the basic inputs, but do not currently include an upload field or other media selection method.

The context for the field defaults to ‘global’, but you can also pass a specific event ID or an array of event IDs. This rule defines where the custom field will show up – with ‘global’, it’ll show up on all add to cart forms. To create custom rules for displaying custom fields, use the ‘mt_apply_custom_field_rules‘ filter.

Example Implementation

add_filter( 'mt_custom_fields', 'create_custom_fields', 10, 1 );
function create_custom_fields( $array ) {
	// Other fields: sanitize callback; input type; input values; display_callback
	$array['test_event_data'] = array( 
		'title'=>"Meal preference", 
		'sanitize_callback'=>'sanitize_callback', 
		'display_callback'=>'display_callback',
		'input_type'=>'select',
		'input_values'=>array( 'Chicken', 'Salad', 'Doughnut' ),
		'context'=> 'global'
	);
	return $array;
}

/* Display callback formats the saved data. $context is 'payment' or 'cart', depending on whether it appears in an admin payment or the user's shopping cart. */
function display_callback( $data, $context='payment' ) {
	return urldecode( $data );
}

/* Sanitize callback cleans the data before saving to the DB */
function sanitize_callback( $data ) {
	return esc_sql( $data );
}

Adding a custom field will also automatically add this data into the Payments reports and will create a template tag so you can use the custom field in your automatic response emails.