We previously talked about ways that you could use filters to add Custom Field information to the signups generated by our WordPress Ajax Campaign Monitor Widgets plugin based on fixed values. But what if you need to capture information from customers and add it to the signups?
Let’s show a quick example of how you might achieve this. In our example we’re going to ask people to choose their favourite colour. For the purposes of this article we’ll assume you’ve already got the field set up at Campaign Monitor, with the tag FavouriteColour (Check out our previous article if that means nothing to you!)
As well as the filters for actually adding the form data to the request sent to Campaign Monitor, the plugin also includes some hooks that you can attach to to generate your form fields on the front end:
- cm_ajax_widget_before_form_fields
- cm_ajax_shortcode_before_form_fields
- cm_ajax_widget_after_form_fields
- cm_ajax_shortcode_after_form_fields
The _before versions are for adding fields before the name and email fields, and the _after versions for if you want them to be added after the name and email. There are versions for widgets and shortcodes, and the hooks get passed the widget or shortcode ID so you can display different information for different forms if you like.
In our example, we want the colour choice to be added to all forms. All we have to do is right a small bit of code that attaches to both the shortcode, and widget hooks, and outputs the HTML for our form field. Here’s a quick example:
function render_extra_form_field ( $context_id ) { echo '<label for="FavouriteColour">Favourite Colour</label>:'; echo '<input class="widefat" type="text" name="FavouriteColour" >'; } add_action( 'cm_ajax_widget_before_form_fields', 'render_extra_form_field' ); add_action( 'cm_ajax_shortcode_before_form_fields', 'render_extra_form_field' );
Then we need to pick up that data when it’s submitted, and include it in the Campaign Monitor request:
function register_extra_custom_field ( $custom_fields, $context_id ) { if ( isset( $_POST['FavouriteColour'] ) ) $custom_fields[] = [ "Key" => 'FavouriteColour', "Value" => $_POST['FavouriteColour'] ]; return $custom_fields; } add_filter( 'cm_widget_custom_fields', 'register_extra_custom_field', 10, 2 ); add_filter( 'cm_shortcode_custom_fields', 'register_extra_custom_field', 10, 2 );
And that’s that – whatever your customers enter into the extra field will be stored in the Custom Fields in your Campaign Monitor account. You have full control of the HTML you add, so you can add checkboxes, select boxes – whatever is appropriate!