Load Gravity Forms scripts for custom field

This post is more than 10 years old.

Gravity Forms is a very easy to use yet flexible tool for building forms in WordPress. It uses quite a bit of JavaScript and custom CSS, so it’s careful to only load its scripts and stylesheets when needed. But if you put a form into a custom field, e.g via Advanced Custom Fields, how will Gravity Forms know it needs to load them?

The simple answer is: you need to tell Gravity Forms. You can do this by detecting whether your custom field has an embedded form, and asking Gravity Forms to load the scripts and CSS that form needs. Don’t worry, there’s some nifty functions already available to help you do this!

NB: some forms need more things than others, for example datepicker fields need specific scripts and CSS that forms without datepickers don’t need. You need to tell Gravity Forms which form will be loaded on your page so that it can determine what it needs to load.

So here’s the code. It’s almost exactly the code I used recently on a custom page template. I put this code in the page template itself (it’s only used for certain pages), but you could put it into functions.php or a simple plugin.

/**
* load Gravity Forms scripts for custom fields
*/
add_action('wp_enqueue_scripts', function() {
    global $post;

    // make sure we have a post, and that Gravity Forms is running
    if (!empty($post->ID) && class_exists('GFFormDisplay')) {
        // get custom field from Advanced Custom Fields
        $custom = get_field('custom_content', $post->ID);
        if (!empty($custom)) {
            // get a list of forms embedded in the custom field
            $forms = GFFormDisplay::get_embedded_forms($custom, $ajax);

            // tell Gravity Forms about each form you'll be loading
            foreach($forms as $form) {
                if (isset($form['id'])) {
                    GFFormDisplay::enqueue_form_scripts($form, $ajax);
                }
            }
        }
    }

}, 20);

And job is done by Gravity Forms, with a little shove in the right direction.