Skip to content

Instantly share code, notes, and snippets.

@devinsays
Created January 25, 2018 23:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devinsays/37fb3504b0544096058e430856685f08 to your computer and use it in GitHub Desktop.
Save devinsays/37fb3504b0544096058e430856685f08 to your computer and use it in GitHub Desktop.
Custom Ninja Forms + Hubspot integration.
<?php
/**
* Hubspot Integration for Ninja Forms.
*
* @package Nano
*/
class NF_Hubspot {
// Hooks into ninja_forms_after_submission
public function init() {
// Define your API key in wp-config.php as a constant
if ( defined( "HAPI_KEY" ) ) {
add_action( 'ninja_forms_after_submission', array( $this, 'process_form_data' ) );
}
}
// Process the Ninja Forms data we want for Hubspot
public static function process_form_data( $form_data ) {
// Ninja Form data
$form_id = $form_data['form_id'];
$fields = $form_data['fields'];
// Hubspot data only processed for form_id(s) 1 & 2
if ( ! in_array( $form_id, array( "1", "2" ) ) ) {
return;
}
// Fields for Hubspot
$first_name = '';
$last_name = '';
$email = '';
// Contact form
if ( "1" === $form_id) {
$name = $fields[1]['value'];
$email = $fields[2]['value'];
}
// Nanofesto form
if ( "2" === $form_id) {
$name = $fields[5]['value'];
$email = $fields[6]['value'];
}
// Our Ninja Forms field does not have first_name & last_name
// So this attempts to split the single "name" field
$name = self::split_name( $name );
// Form Data to Post
$data['properties'][] = array( "property" => "email", "value" => $email );
$data['properties'][] = array( "property" => "firstname", "value" => $name[0] );
$data['properties'][] = array( "property" => "lastname", "value" => $name[1] );
self::post_data_to_hubspot( $data );
}
// Splits the name field into first_name and last_name
// https://stackoverflow.com/questions/13637145/split-text-string-into-first-and-last-name-in-php
public static function split_name( $name ) {
$name = trim( $name );
$last_name = ( strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name );
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
return array( $first_name, $last_name );
}
// Posts our data to Hubspot
public static function post_data_to_hubspot( $data ) {
$args = array(
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => json_encode( $data )
);
$api_url = 'https://api.hubapi.com/contacts/v1/contact?hapikey=' . HAPI_KEY;
$response = wp_remote_post( $api_url, $args );
// Log $response if $error
if ( is_wp_error( $response ) ) {
error_log( $response->get_error_message() );
}
}
}
$hubspot = new NF_Hubspot();
$hubspot->init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment