';
echo get_new_contact_field( '0', array( 'displayorder' => 1 ) );
}
// Now we need to have a hidden blank field for jQuery to use
// as a template to auto-magically add new fields to the page
?>
"
. "$fieldname"
. '';
}
/**
* Display a new field in the admin AJAX Contact meta box
*
* @param integer $sequence The sequential number for this contact field
* @param array $data The data to pre-populate this field with (if any)
**/
function get_new_contact_field( $sequence, $data = array() ) {
// If any necessary fields are empty, fill them with the default value
$fieldname = ( key_exists( 'fieldname', $data ) ) ? $data['fieldname'] : 'New Field';
$fieldtype = ( key_exists( 'fieldtype', $data ) ) ? $data['fieldtype'] : 'input';
$fieldoptions = ( key_exists( 'fieldoptions', $data ) ) ? $data['fieldoptions'] : '';
$displayorder = ( key_exists( 'displayorder', $data ) ) ? $data['displayorder'] : '';
$fieldrequired = ( key_exists( 'fieldrequired', $data ) ) ? $data['fieldrequired'] : '';
$fieldvalidation = ( key_exists( 'fieldvalidation', $data ) ) ? $data['fieldvalidation'] : 'none';
// Html for a new contact form field
return "
"
. '
Field Editor
'
. '
'
. ""
. ""
. '
'
. '
'
. ""
. "'
. '
'
. '
'
. ""
. ""
. '
'
. '
'
. ""
. ""
. '
'
. '
'
. ""
. "'
. '
'
. '
'
. ""
. "'
. '
'
. '
'
. ""
. ''
. '
'
. '
';
}
/**
* Save the iwacontact meta box data on save_post action
*
* @param integer $post_id The post ID
**/
function iwacontact_save_meta( $post_id ) {
// If our hidden field wasn't in the submitted data, return (don't save)
if ( !key_exists( 'iwajax_contact', $_POST ) )
return $post_id;
// If the nonce couldn't be verified, return (don't save)
if ( !wp_verify_nonce( $_POST['iwajax_contact'], plugin_basename(__FILE__) ) )
return $post_id;
// If doing an autosave, return (don't save)
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
// If the post_type is not a page, return (don't save)
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return $post_id;
}
$form_fields = array(); // Form fields associative array
$field_names = array(); // Field names array
// For each item in the $_POST array
foreach ( $_POST as $key => $value ) {
// Using a regex, check if it's one of our attribute fields (e.g. iwacf_fieldname_1)
if ( preg_match( '/^iwacf\_[a-z]+\_[0-9]+$/', $key ) ) {
// Split the array key on _ (e.g. ( [0] => iwacf, [1] => fieldname, [2] => 1)
$attrs = preg_split( '/\_/', $key );
// Assign this attribute field's serial number to $field_no
$field_no = $attrs[2];
// If this is a fieldname attribute, add the value of it to the $field_names array
if ( $attrs[1] == 'fieldname' )
array_push( $field_names, $value );
// Create a new associative array containing the attribute name => value
$array_item = array( $attrs[1] => $value );
// If the $form_fields associative array does not contain an array with this field number
if ( !key_exists( $field_no, $form_fields ) || !is_array( $form_fields[$field_no] ) )
$form_fields[$field_no] = array(); // Add it to $form_fields as an empty array
// Merge this attribute name=>value pair on to the $form_fields array
$form_fields[$field_no] = array_merge( $form_fields[$field_no], $array_item );
}
}
// Now $form_fields is populated with all our attribute fields like;
// array( [0] => array( 'fieldname' => 'My First Field', 'fieldtype' => 'input' ) ,
// [1] => array( 'fieldname' => 'My Second Field', 'fieldtype' => 'selectbox' ) )
$iwacontact_data = array();
$iwacontact_data_str = '';
$count = 0;
// For each associative array in our $form_fields array
foreach ( $form_fields as $field ) {
// Increase the counter
$count++;
// Make the field name safe to be turned in to a html ID/name attribute
$safe_field_name = mb_strtolower( trim( $field['fieldname'] ) ); // Clean leading/trailing white space and make the string lower case
$safe_field_name = preg_replace( '/\ /', '_', $safe_field_name ); // Replace any spaces with underscores (_)
$safe_field_name = preg_replace( "/[^a-zA-Z0-9-_]/", "", $safe_field_name ); // Remove any non alphanumeric characters
// Set some defaults in case anything is left empty
$displayorder = ( key_exists( 'displayorder', $field ) ) ? $field['displayorder'] : $count;
$fieldoptions = ( key_exists( 'fieldoptions', $field ) ) ? $field['fieldoptions'] : '';
$fieldrequired = ( key_exists( 'fieldrequired', $field ) ) ? $field['fieldrequired'] : '';
// Turn this field's attributes in to an array
$field_data = array(
$safe_field_name,
$displayorder,
$field['fieldtype'],
$field['fieldname'],
$fieldoptions,
$fieldrequired,
$field['fieldvalidation']
);
// Turn the array in to a '::' separated string
$field = join( '::', $field_data );
// Add the field on to the $iwacontact_data array
array_push( $iwacontact_data, $field );
}
// Turn the fields in $iwacontact_data in to a ';;' separated string
$iwacontact_data_str = join( ';;', $iwacontact_data );
// Update all the post custom fields with our meta data
update_post_meta( $post_id, 'iwacontact_data', $iwacontact_data_str );
update_post_meta( $post_id, 'iwacontact_sendto', trim( $_POST['iwacf_sendto'] ) );
update_post_meta( $post_id, 'iwacontact_subject', trim( $_POST['iwacf_subject'] ) );
update_post_meta( $post_id, 'iwacontact_from', trim( $_POST['iwacf_from'] ) );
update_post_meta( $post_id, 'iwacontact_submit_value', trim( $_POST['iwacf_submit_value'] ) );
}
add_action( 'save_post', 'iwacontact_save_meta' );
/**
* Custom sorting function that works with usort()
* to sort custom field arrays by a child var's value
**/
function sort_fields( $a, $b ) {
if ( $a[1] == $b[1] ) return 0;
return ( $a[1] < $b[1] ) ? -1 : 1;
}
/**
* Gets the contact form for the requested post ID
*
* @param integer $post_id The post ID
**/
function get_contact_form( $post_id ) {
// Get the post object for this post
$post = get_post( $post_id );
// Get the custom fields for this post
$fields = get_post_custom( $post_id );
// Set the error variable
$error = false;
// If it has our custom field iwacontact_data
if ( key_exists( 'iwacontact_data', $fields ) ) {
// Start building the form html
$form = '';
// Return the form html
return $form;
}
}
function trim_value( &$value ) {
$value = trim($value);
}
/**
* The call back function for our custom
* short code [insert_ajaxcontact]
*
* @param array $atts The attributes
**/
function insert_ajaxcontact( $atts ) {
$the_ID = ( is_array( $atts ) && key_exists( 'id', $atts ) ) ? $atts['id'] : get_the_ID();
return get_contact_form( $the_ID );
}
add_shortcode( 'insert_ajaxcontact', 'insert_ajaxcontact' );
/**
* The AJAX handler function that catches AJAX
* post submissions and processes them. This function
* also prepares and sends the contact notification email.
**/
function ajax_handler() {
// If our hidden field 'iwac_submitted' exists in the $_POST array
if ( key_exists( 'iwac_submitted', $_POST ) ) {
// Set the blog name to $blog_name
$blog_name = get_bloginfo( 'name' );
// Start the email body text
$email_body = "There has been a new contact form submission at $blog_name";
// Get the custom fields array for this post
$fields = get_post_custom( $_POST['iwac_form_id'] );
// Get the contents of our custom field 'iwacontact_data'
$iwacontact_data = $fields['iwacontact_data'][0];
// Find each field by splitting the custom field contents on ';;'
$form_fields = preg_split( '/\;\;/', $iwacontact_data );
// Create a new array for the correctly ordered form fields
$ordered_fields = array();
// For each form field
foreach ( $form_fields as $field ) {
// Find the field attributes by splitting the string on '::'
$field_attrs = preg_split( '/\:\:/', $field );
// Add them to our ordered fields array
array_push( $ordered_fields, $field_attrs );
}
// Sort the ordered fields array by the specified display order
usort( $ordered_fields, "sort_fields" );
// Set the $has_error variable to false
$has_error = false;
// For each field in our correctly ordered form field array
foreach ( $ordered_fields as $field ) {
// Place the field attributes in an easier to use associative array
$field_vars = array(
'element_id' => $field[0],
'displayorder' => $field[1],
'fieldtype' => $field[2],
'fieldname' => $field[3],
'fieldoptions' => $field[4],
'fieldrequired' => $field[5],
'fieldvalidation' => $field[6]
);
// Set the submitted value for this field
// If it was an array (ie multiple select box), make it a string
$submitted_value = ( is_array( $_POST[$field_vars['element_id']] ) ) ? join( ',', $_POST[$field_vars['element_id']] ) : $_POST[$field_vars['element_id']];
// Check for empty required fields
if ( $field_vars['fieldrequired'] == '1' && trim( $submitted_value ) == '' ) {
$has_error = true;
}
// Or non-valid email addresses
elseif ( $field_vars['fieldvalidation'] == 'email' && !preg_match( '/^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$/i', $submitted_value ) ) {
$has_error = true;
}
// Otherwise, add the field name and it's submitted value to our email body variable
else {
$field_value = ( is_array( $_POST[ $field_vars['element_id'] ] ) ) ? implode( ', ', $_POST[ $field_vars['element_id'] ] ) : trim( $_POST[ $field_vars['element_id'] ] );
$email_body .= "\n\n" . $field_vars['fieldname'] . ":\n" . $field_value ;
}
}
// If no errors occurred
if ( !$has_error ) {
// Set the subject, from and to address as the one specified in the post custom fields
$from = $fields['iwacontact_from'][0];
$email_to = $fields['iwacontact_sendto'][0];
$subject = $fields['iwacontact_subject'][0];
// Set the email body as the variable we where adding content to before
$body = $email_body;
// Set the email from headers
$headers = 'From: ' . get_bloginfo( 'name' ) . " <$from>" . "\r\n" . 'Reply-To: ' . $from;
// Use wp_mail to send the message
wp_mail( $email_to, $subject, $body, $headers );
// If there was a field named send_copy and it's value was true, send a copy to the form submitter
if ( key_exists( 'send_copy', $_POST ) && $_POST['send_copy'] == 'true' ) {
$subject = 'Your email to ' . get_bloginfo( 'name' );
$headers = 'From: ' . get_bloginfo( 'name' ) . " <$from>";
wp_mail( $email, $subject, $body, $headers );
}
}
}
}
add_action( 'init', 'ajax_handler' );
// Our init functions
function acontact_init() {
$labels = array(
'name' => _x( 'Forms', 'post type general name'),
'singular_name' => _x( 'Form', 'post type singular name'),
'add_new' => _x( 'Add New', 'form'),
'add_new_item' => __( 'Add New Form'),
'edit_item' => __( 'Edit Form'),
'new_item' => __( 'New Form'),
'view_item' => __( 'View Form'),
'search_items' => __( 'Search Forms'),
'not_found' => __( 'No forms found'),
'not_found_in_trash' => __( 'No forms found in Trash'),
'parent_item_colon' => '',
'menu_name' => 'Contact Forms'
);
$args = array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => false,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => false,
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'menu_position' => 20,
'menu_icon' => plugin_dir_url( __FILE__ ) . 'images/post-type-icon.png',
'supports' => array( 'title' )
);
register_post_type( 'iwacontactform', $args );
wp_register_style( 'ajax-contact-css', plugin_dir_url( __FILE__ ) . 'ajax-contact.css' );
wp_register_script( 'ajax-contact', plugin_dir_url( __FILE__ ) . 'ajax-contact.js', array( 'jquery' ) );
wp_enqueue_style( 'ajax-contact-css' );
wp_enqueue_script( 'ajax-contact' );
}
add_action( 'init', 'acontact_init' );
// Our admin init functions
function acontact_admin_init() {
wp_register_style( 'ajax-contact-admin-css', plugin_dir_url( __FILE__ ) . 'ajax-contact-admin.css' );
wp_register_script( 'ajax-contact-admin', plugin_dir_url( __FILE__ ) . 'ajax-contact-admin.js', array( 'jquery' ) );
wp_enqueue_style( 'ajax-contact-admin-css' );
wp_enqueue_script( 'ajax-contact-admin' );
}
add_action( 'admin_init', 'acontact_admin_init' );