// WordPress Hooks
add_shortcode( 'ccom_contact_form', function( $atts ) {
return ccom_contact_form::print_form();
} );
add_action( 'rest_api_init', function() {
ccom_contact_form::rest_api_init();
} );
// Plugin Class
class ccom_contact_form {
// Settings
private static $zendesk_url = 'https://MY-SUBDOMAIN.zendesk.com/api/v2/requests.json';
private static $username = '[email protected]/token';
private static $password = 'TOKEN-GOES-HERE';
// Shortcode To Render Form
static function print_form() {
$current_user = get_current_user_id() ? wp_get_current_user() : false;
ob_start();
?>
<form id="contact_form" method="POST" action="/wp-json/ccom_contact_form/v1/submit">
<?php if( $current_user ) { ?>
<input type="hidden" name="redirect" value="/my-account/">
<input type="hidden" name="name" value="<?php echo get_user_meta( $current_user->ID, 'first_name', true ); ?>">
<input type="hidden" name="email" value="<?php echo $current_user->user_email; ?>">
<?php } else { ?>
<input type="hidden" name="redirect" value="/">
<p>
<input type="text" name="name" required="required"
placeholder="First Last" aria-label="Your name">
</p>
<p>
<input type="email" name="email" required="required"
placeholder="[email protected]" aria-label="Your email address">
</p>
<?php } ?>
<p>
<textarea cols="30" rows="5" name="message" required="required"
placeholder="Enter your message here." aria-label="Your message"></textarea>
</p>
<p>
<input class="button" type="submit" value="Send message">
</p>
</form>
<?php
$ccom_contact_form = isset( $_GET['ccom_contact_form'] )
? $_GET['ccom_contact_form'] : '';
switch( $ccom_contact_form ) {
case 'success':
$tid = isset( $_GET['ticket_id'] ) ? $_GET['ticket_id'] : '';
echo '<p>Thank you for your message. Your ticket number is #' . $tid . '</p>';
break;
case 'error':
$msg = isset( $_GET['message'] ) ? $_GET['message'] : '';
echo '<p>We\'re sorry. There was an error with your submission (' . $msg . ').</p>';
break;
}
return ob_get_clean();
}
// REST API Endpoint
static function rest_api_init() {
register_rest_route(
'ccom_contact_form/v1',
'/submit',
[
'callback' => [
'ccom_contact_form',
'submit'
],
'methods' => 'POST',
'permission_callback' => '__return_true',
]
);
}
// Form Submissions
static function submit( WP_REST_Request $request ) {
// Get Submission
$field_redirect = $request->get_param( 'redirect' );
$field_name = $request->get_param( 'name' );
$field_email = $request->get_param( 'email' );
$field_message = $request->get_param( 'message' );
// Missing Data Error
if( ! $field_name ) {
exit(
wp_safe_redirect(
$field_redirect . '?ccom_contact_form=error&message=Name+missing'
)
);
}
if( ! $field_email ) {
exit(
wp_safe_redirect(
$field_redirect . '?ccom_contact_form=error&message=Email+missing'
)
);
}
if( ! $field_message ) {
exit(
wp_safe_redirect(
$field_redirect . '?ccom_contact_form=error&message=Message+missing'
)
);
}
// Append Tracing To Message
$ip_address = empty( $_SERVER['HTTP_CF_CONNECTING_IP'] )
? $_SERVER['REMOTE_ADDR'] : $_SERVER['HTTP_CF_CONNECTING_IP'];
$field_message .= sprintf(
"\n\nIP Address: %s\n\nUser Agent: %s",
$ip_address, $_SERVER['HTTP_USER_AGENT']
);
if( ! empty( $_SERVER['HTTP_CF_IPCOUNTRY'] ) ) {
$field_message .= sprintf(
"\n\nGeolocation: %s", $_SERVER['HTTP_CF_IPCOUNTRY']
);
}
// Submit Zendesk Ticket
$response = wp_remote_post(
self::$zendesk_url,
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Basic ' . base64_encode(
self::$username . ':' . self::$password
),
],
'body' => json_encode(
[
'request' => [
'subject' => 'Website Contact Form',
'comment' => [
'body' => $field_message,
],
'requester' => [
'locale_id' => '1',
'name' => $field_name,
'email' => $field_email,
],
'priority' => 'normal',
],
]
),
'timeout' => 30,
]
);
// Communication Error
if( is_wp_error( $response ) ) {
exit(
wp_safe_redirect(
$field_redirect . '?ccom_contact_form=error&message=Comm+failure'
)
);
}
// Get Response Body And ID
$response = wp_remote_retrieve_body( $response );
$response = json_decode( $response );
$tid = isset( $response->request->id )
? intval( $response->request->id ) : '';
// Zendesk Error
if( ! $tid ) {
$response = isset( $response->description )
? $response->description : print_r( $response, true );
exit(
wp_safe_redirect(
$field_redirect . '?ccom_contact_form=error&message=Zendesk+rejected:+' . $response
)
);
}
// Zendesk Success
exit(
wp_safe_redirect(
$field_redirect . '?ccom_contact_form=success&ticket_id=' . $tid
)
);
}
}
Zendesk contact form and integration
Adds shortcode `ccom_contact_form` to print Zendesk contact form. Shows Name and Email fields for unauthenticated traffic. Be sure to set your Zendesk URL, admin email address and API token in the settings area. Set this snippet to run everywhere in Code Snippets.
How to use
- Log into a staging, development, or locally hosted clone of your site
- Install and activate Code Snippets
- WP Admin > Snippets > Add New
- Copy and paste the code from the Description tab above
- Check to ensure formatting came over properly and no syntax errors show up in the editor
- Customize the code as desired
- Add a meaningful title
- Select whether to run on front-end or back-end (or both)
- Click “Save and Activate”
- Test your site to ensure it works
- Disable if any problems, or recover
- Repeat for live environment
License
All code snippets are licensed GPLv2 (or later) matching WordPress licensing.
Disclaimer of warranty:
Except when otherwise stated in writing the copyright holders and/or other parties provide the program as-is without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose.
Support
- Describe the issue and what you’ve observed.
- Describe your expected outcome(s).
- List steps to reproduce the issue.
- Optionally provide screen-shot or video URLs.
