Show a Gravity Form with a Click of a Button

On a recent project, I wanted to add a Gravity Form to a post/page, but hide it behind a button so that it would only show if the user clicked on the button (the form is rather long). The client needs to be able to do this on her own, so my solution for her needed to be something accessible from the post editor, and easy to implement. A google search gave me a step in the right direction, with a solution which involved loading the form using Ajax. I encountered issues with this, though, with the form not submitting properly (quite likely due to something I did wrong).

After a fair amount of grappling with the code, I was able to modify it to work with a simple bit of jQuery, no ajax required (although it is important that the form be submitted via Ajax). It works by using the default Gravity Form shortcode output, and then you just add a little bit of text to it, which may take some client training, but since the shortcode is visible in both the text and the visual editors, it should be pretty doable. So, let me show you how I did this.

Note: this tutorial requires Gravity Forms (not an affiliate link), a premium forms plugin. It should work with any theme.

Code: Filter the Shortcode

I’ve set this up within a unique file in my theme/plugin, but you can put this code into your theme’s functions.php file if you like. Just please remember, practice safe coding, back up your site and files, etc. etc.

<?php
/**
* Helper Functions for Gravity Forms.
* @package Leaven
*/
add_filter( 'gform_shortcode_button', 'leaven_gravity_button_shortcode', 40, 3 );
/**
* Add the "button" action to the gravityform shortcode
* e.g. [gravityform id="1" action="button" text="button text"]
* @param $shortcode_string
* @param $attributes
* @param $content
*
* @return string|void
*/
function leaven_gravity_button_shortcode( $shortcode_string, $attributes, $content ) {
if ( 'button' !== $attributes['action'] ) {
return $shortcode_string;
}
$defaults = array(
'title' => true,
'description' => false,
'id' => 0,
'name' => '',
'field_values' => '',
'tabindex' => 1,
'text' => __( 'Click to open form', 'leaven' ),
);
$attributes = wp_parse_args( $attributes, $defaults );
if ( $attributes['id'] < 1 ) {
return __( 'Missing the ID attribute.', 'leaven' );
}
return leaven_build_gravity_button( $attributes );
}
/**
* Build the button/form output.
* @param $attributes array shortcode arguments
*
* @return string
*/
function leaven_build_gravity_button( $attributes ) {
$form_id = absint( $attributes['id'] );
$text = esc_attr( $attributes['text'] );
$onclick = "jQuery('#gravityform_button_{$form_id}, #gravityform_container_{$form_id}').slideToggle();";
$html = sprintf( '<button id="gravityform_button_%1$d" class="gravity_button" onclick="%2$s">%3$s</button>', esc_attr( $form_id ), $onclick, esc_attr( $text ) );
$html .= sprintf( '<div id="gravityform_container_%1$d" class="gravity_container" style="display:none;">', esc_attr( $form_id ) );
$html .= gravity_form( $form_id, $attributes['title'], $attributes['description'], false, $attributes['field_values'], true, $attributes['tabindex'], false );
$html .= '</div>';
return $html;
}
view raw gravity.php hosted with ❤ by GitHub

What we have here are two functions: the first modifies the Gravity Forms shortcode so that it knows to create the button; the second handles the actual button and form output. Although you could do this all in one function, I chose to separate for two reasons: 1) it actually simplifies the code and makes it easier for me to understand; and 2) the first function deals with just the shortcode bits, while the second does the heavy lifting without requiring anything from me.

One client for whom I’ve implemented this solution is in the process of setting up an ecommerce store, but they sell a mix of stock and custom items. The custom items cannot be sold through the store at all, because they vary so much. For those items, we’ve disabled the cart functionality, and in the single product template, we’ve added a bit to include a “Request a Quote” button, which uses the second function (here’s the code I used for that–definitely not the only way to do this, but fairly easy to implement).

This honors most of the default Gravity Form shortcodes, except for enabling Ajax–since that’s necessary for the submission to work properly, the modified shortcode always forces Ajax for the form submission.

Modify the Gravity Form Shortcode

Now that your code is in place, you just need to know how to make it work. Pretty easy. At its most basic, when you add a Gravity Form to your post/page, the shortcode looks like this:

[gravityform id="1"]

Go ahead and add your form to your post/page, and then add just two things to the shortcode: 1) an action; and 2) text for your button:

[gravityform id="1" action="button" text="Click this button"]

The action is required and must be button, or else it will just be ignored. The text is optional: the default is set back in that first function: Click to open form. This allows you to use whatever you want for the button text.

Here’s our end result:

Hide a Gravity Form Behind a Button

Bonus Round: Be Kind to Those With No JavaScript

I know this is less common, but if you want to consider your users who might not have JavaScript enabled in their browser, for whatever reasons, you need to do just a bit more work. If your theme already includes code to detect whether JavaScript is enabled, follow your standard practice and style the button and form so that they’ll show no matter what.

In my theme, I have a bit of code which assigns a class of no-js to the body output initially (my code is based on this nifty plugin by Gary Jones), and then changes it to js, using JavaScript. So I can do this styling in my theme:

.no-js .gravity_button {
display: none;
}
.no-js .gravity_container {
display: block !important; // !important required to override inline style
}
view raw style.css hosted with ❤ by GitHub

If I didn’t include this, my non-JS users would see the button, but no form. This way, they don’t see the button, but they do see the form, and all is well.

So there you have it–some fairly easy to drop in code to make it a little more friendly to add a longish form to a post or page without disrupting the content around it, or having to create a new page just to hold the form. Hope you’ve found it helpful!

Do something awesome. Tell a friend:

subscribe by email

If you're an email kind of person, that's totally cool. Go ahead and sign up here to get the latest blog entries in your inbox! No worries, I never share your address.
  • This field is for validation purposes and should be left unchanged.

Reader Interactions

Comments

  1. August 3, 2016

    This is exactly the kind of thing I needed – thank you so much. A question, though: Is there a way to hide the description and title from the from, when it is loaded this way. The normal gravity forms short code doesn’t work.

    • August 3, 2016

      This should honor whatever arguments you pass through the Gravity shortcode (if you don’t specify, the form title will show, but the description should not).

    • November 8, 2016

      Probably it can, if you can do the js work to make it happen. I don’t do much with popups personally.

  2. November 10, 2016

    Hi Robin,

    I know you implemented this in SixTenPress, and it’s one of the nice benefits with installing the plugin (getting it to work out of the box). In this current project I am working on I need to include some HTML in the button text (a couple of <em> elements to be precise. )

    Since you are escaping the text variable in the output, that doesn’t work.
    I can manually hack the plugin by changing line ~53 from esc_attr( $text ) to $text but that means that any plugin updates would override my changes. Is there a filter or some other more elegant solution to deal with this issue?

    I’m all ears if you have any ideas!

    • November 11, 2016

      That’s a fair point, and a need I had not considered. I can change the escaping function in the function there to wp_kses_post(), which will allow markup like what you’re wanting. It will be in the next update.

  3. July 20, 2017

    Thank you for this. I am going to give it a try. Not being a seasoned developer. If I wanted to put this into a file other than functions.php. How do I do that? Is there any quick advice you can offer – or something to point me to read.

    Thanks
    Mike

    • July 27, 2017

      As long as it is where WordPress can “see” it, that’s all you need. For instance, you could create a completely new PHP file and put the code in there, and you would just have to add a line to your functions.php file to tell WordPress to load the new file.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Bars Code Check chevron-down chevron-left chevron-right chevron-up Envelope Laptop Search Times Facebook GitHub Google Plus Instagram LinkedIn Pinterest Twitter WordPress Logo Wordpress Simple