An Easy Way To Embed HubSpot Forms In WordPress

HubSpot is quite impressive and for marketers the first choice. With HubSpot forms, you are able to enrich user data in conjunction with user activities. In this example, I will show you an easy way to embed HubSpot forms in WordPress based on a shortcode function.

Creating a HubSpot form

First of all, we create a simple form in HubSpot with some input and select fields. It’s not necessary to use a large amount of form fields as in this example.

hubspot-create-form

If you’re done creating the form fields, select (on the bottom of the page) Actions and Embed to go further.

hubspot-form-actions-embed-code

In the emerging modal, you enter a fictive domain as redirect URL and grab the javascript code snippet beneath the redirect URL field which includes the portalid, the unique formid and saves this for later use.

hubspot-form-actions-embed-code-modal-marked

Creating the WordPress Shortcode

add_shortcode('hubspot_form', function($atts)
{
    extract(shortcode_atts(array(
        'form_id'      => null,
        'redirect_url' => null
    ), $atts));

    ...

});

The formid attribute is required and needed to show the HubSpot form. The redirecturl is an optional attribute and can be omitted while using the redirect URL, which you define in the HubSpot Modal. Let’s check and validate the form_id:

add_shortcode('hubspot_form', function($atts)
{
    extract(shortcode_atts(array(
        'form_id'      => null,
        'redirect_url' => null
    ), $atts));

    if( !is_null($form_id) and preg_match('/w{0,8}-d{4}-d{4}-d{4}-w{0,8}/i', $form_id) )
    {
        ...
    }

});

Last but not least, the rest of the WordPress shortcode script:

add_shortcode('hubspot_form', function($atts)
{
    extract(shortcode_atts(array(
        'form_id'      => null,
        'redirect_url' => null
    ), $atts));

    // if form id is passed and validate, go further building the script part
    if( !is_null($form_id) and preg_match('/w{0,8}-d{4}-d{4}-d{4}-w{0,8}/i', $form_id) )
    {
        $hubspot_form =
            array(
                'portalId' => 'xxxxx', // hubspot account identifier
                'formId'   => $form_id, // your unique form id
                )
            );

        // check whether $redirect_url attribute was passed
        if( !is_null($redirect_url) )
        {
            // set the redirect url dynamically
            $hubspot_form['redirectUrl'] = $redirect_url;
        }

        // turn output buffering on
        ob_start();
        ?>
        <script charset="utf-8" src="//js.hsforms.net/forms/current.js"></script>
        <script>
            // initiate the hubspot form and pass the formId and portalId attributes
            hbspt.forms.create( <?php echo json_encode( $hubspot_form ); ?> );
        </script>
        <?php
        //  copy the internal buffer into a string variable
        $html_form = ob_get_contents();

        // discard and turn off the output buffer
        ob_end_clean();

        // return the html/javascript code
        return $html_form;
    }

});

The portalId is your HubSpot account identifier (http://help.hubspot.com/articles/KCS_Article/Where-can-I-find-my-HUB-ID) and used globally for all API-calls.

Using the WordPress Shortcode

The regular shortcode call in posts/pages is.[hubspot_form form_id="xxxxxx" redirect_url="http://domain.com/redirect-page"] If you want to use that shortcode in a custom post-/page-template, you can use do_shortcode('[hubspot_form form_id="xxxxxx" redirect_url="http://domain.com/redirect-page"]');.

Finally, a slightly more detailed example without comments and based on HubSpot form-api:

add_shortcode('hubspot_form', function($atts)
{
    extract(shortcode_atts(array(
        'form_id'      => null,
        'redirect_url' => null
    ), $atts));

    if( !is_null($form_id) and preg_match('/w{0,8}-d{4}-d{4}-d{4}-w{0,8}/i', $form_id) )
    {
        $hubspot_form =
            array(
                'portalId'          => 'xxxxxxx',
                'formId'            => $form_id,
                'submitButtonClass' => 'ui button small submit-download-form',
                'validationOptions' => array(
                    'grouped'       => true,
                    'inputEvent'    => 'keyup',
                    'message'       => '<div/>',
                    'messageClass'  => 'ui red pointing below label',
                    'lang'          => ICL_LANGUAGE_CODE,
                    'localization'  => array(
                        ICL_LANGUAGE_CODE => array(
                            ':email'           => __('Please enter a valid email address', 'xyz'),
                            '[required]'       => __('This field ist required', 'xyz'),
                            'select[required]' => __('A selection is required', 'xyz')
                        )
                    )
                )
            );

        if( !is_null($redirect_url) )
        {
            $hubspot_form['redirectUrl'] = $redirect_url;
        }

        ob_start();
        ?>
        <script charset="utf-8" src="//js.hsforms.net/forms/current.js"></script>
        <script>
            form_options = {
                onFormReady: function() {},
                onBeforeValidationInit: function() {},
                onBeforeFormInit: function() {},
            }
            hbspt.forms .create( $.extend( true, form_options, <?php echo json_encode( $hubspot_form ); ?> ) );
        </script>
        <script>hbspt.forms.create( <?php echo json_encode( $hubspot_form ); ?> );</script>
        <?php
        $html_form = ob_get_contents();
        ob_end_clean();

        return $html_form;
    }
});

The ICLLANGUAGECODE constant comes from The WordPress Multilingual Plugin and can be replaced with a double-digit language code.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
Tags:
forms