Load Gravity Forms stylesheets in page head

This post is more than 9 years old.

Gravity Forms normally loads its stylesheets in the page head, where they belong. It does that only on pages which have forms, which is nice. If you use a widget to host your form, however, it can’t detect that until it renders the widget… too late to load the stylesheets in the head. At that point, it just pulls them directly into the page body.

That’s not normally a problem, as long as you aren’t trying to override Gravity Forms’ stylesheets. Which we normally do when we’re building a nice shiny new theme for a website!

One way to get around the problem is to tell Gravity Forms not to load its stylesheets (it’s a setting), and take over styling the forms yourself. If you think that sounds like a lot of work, well… maybe not so much if you incorporate some basic styling from a project like Gravity Forms Sass.

An easier way around the problem, however, is to work out what forms you will be loading in widgets on your pages, and ask Gravity Forms to load their required stylesheets. NB: you need to know the form IDs, because Gravity Forms only loads the stylesheets needed for each form that will be displayed, and to do that it needs to examine each form.

/**
* preload Gravity Forms' stylesheets in head
*/
add_action('wp_enqueue_scripts', function() {
    if (function_exists('gravity_form_enqueue_scripts')) {
        // newsletter subscription form
        gravity_form_enqueue_scripts(5);
    }
});

Job is done, in head, so that we can restyle that sucker !important