Gravity Wiz

Magically enhanced tutorials, snippets and plugins for Gravity Forms!

  • Gravity Perks
    • Gravity Perks
    • Tutorials & Snippets
    • About
  • Support
    • Documentation
    • Support
    • Account

Submit a Gravity Form to Access Content

This plugin provides a simple way to protect your content, requiring the visitor to submit a form in order to gain access.

Last updated April 11, 2018 | Written by David Smith 189 Comments

  • June 21, 2017: Improved support for automatically showing required form if no required message is specified.

  • March 2, 2017: Updated submitted forms cookie to be persistent by default. Added new "is_persistent" option to disable this.

  • March 1, 2017: Added support for "gwsa_requires_submission_redirect" option to allow automatically redirecting to a specific page if the user requires access.

  • March 23, 2016: Added support for requiring a form to be submitted before any page can be accessed. Added support for storing submitted forms in user meta.

  • March 3, 2015: Added support for shortcodes in "gwsa_requires_submission_message" custom field. Fixed issue where json_decode() did not return an array.

Show All Updates
View DemoShow CodeDownload Plugin
<?php
/**
* Gravity Wiz // Gravity Forms // Submit to Access
*
* Require that a form be submitted before a post or page can be accessed.
*
* @version 1.7
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link https://gravitywiz.com/submit-gravity-form-access-content/
*
* ### WordPress Plugin Headers ###
*
* Plugin Name: Gravity Forms Submit to Access
* Plugin URI: https://gravitywiz.com/submit-gravity-form-access-content/
* Description: Require that a form be submitted before a post or page can be accessed.
* Author: Gravity Wiz
* Version: 1.7
* Author URI: https://gravitywiz.com
*/
class GW_Submit_Access {
public function __construct( $args = array() ) {
// set our default arguments, parse against the provided arguments, and store for use throughout the class
$this->_args = wp_parse_args( $args, array(
'requires_submission_message' => __( 'Oops! You do not have access to this page.' ),
'bypass_cache' => false,
'loading_message' => '', // set later so we can use GFCommon to get URL to GF spinner,
'enable_user_meta' => false,
'is_persistent' => true,
) );
// do version check in the init to make sure if GF is going to be loaded, it is already loaded
add_action( 'init', array( $this, 'init' ) );
}
public function init() {
// make sure we're running the required minimum version of Gravity Forms
if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
return;
}
// setting later so we can use GFCommon::get_base_url() to get GF's spinner URL
if( empty( $this->_args['loading_message'] ) ) {
$this->_args['loading_message'] = '<span class="gwsa-loading">Loading content... <img src="' . GFCommon::get_base_url() . '/images/spinner.gif" /></span>';
}
add_action( 'wp', array( $this, 'check_global_requirements' ), 5 );
add_action( 'admin_init', array( $this, 'check_global_requirements' ), 5 );
add_action( 'wp', array( $this, 'check_for_access_redirect' ) );
add_action( 'gform_pre_submission', array( $this, 'add_submitted_form' ) );
add_filter( 'the_content', array( $this, 'maybe_hide_the_content' ) );
add_action( 'wp_ajax_gwas_get_content', array( $this, 'ajax_get_content' ) );
add_action( 'wp_ajax_nopriv_gwas_get_content', array( $this, 'ajax_get_content' ) );
add_shortcode( 'gwsa', array( $this, 'do_gwsa_shortcoee' ) );
}
public function check_global_requirements() {
if( current_user_can( 'administrator' ) && is_admin() ) {
return;
}
$global_posts = $this->get_global_posts();
if( empty( $global_posts ) ) {
return;
}
// if we're already on a global post, don't do anything
$object = get_queried_object();
if( is_a( $object, 'WP_Post' ) && in_array( $object->ID, wp_list_pluck( $global_posts, 'ID' ) ) ) {
return;
}
foreach( $global_posts as $global_post ) {
if( ! $this->has_access( $global_post->ID ) ) {
wp_redirect( get_permalink( $global_post ) );
exit;
}
}
}
public function get_global_posts() {
$query = array(
'post_type' => 'any',
'meta_query' => array(
'relation' => 'or',
array(
'key' => 'gwsa_require_submission',
'value' => 'global'
),
),
);
if( is_user_logged_in() ) {
$query['meta_query'][] = array(
'key' => 'gwsa_require_submission',
'value' => 'global_logged_in'
);
}
$query = apply_filters( 'gfsa_get_global_posts_query', $query );
$global_posts = get_posts( $query );
return $global_posts;
}
public function check_for_access_redirect() {
global $post;
if( is_admin() ) {
return;
}
if( ! $post || ! $this->requires_access( $post->ID ) || $this->has_access( $post->ID ) ) {
return;
}
$url = $this->get_requires_submission_redirect( $post->ID );
if( $url ) {
wp_redirect( $url );
exit;
}
}
public function maybe_hide_the_content( $content ) {
global $post;
if( ! $this->requires_access( $post->ID ) ) {
return $content;
}
if( $this->_args['bypass_cache'] ) {
$content = $this->cache_bypass_content( $content );
} else if( ! $this->has_access( $post->ID ) ) {
$content = $this->get_requires_submission_message( $post->ID );
}
return $content;
}
function cache_bypass_content( $content ) {
global $post;
ob_start();
?>
<div id="gwsa-content">
<?php echo $this->_args['loading_message']; ?>
</div>
<script type="text/javascript">
var ajaxUrl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
( function( $ ) {
$.post( ajaxUrl, {
action: 'gwas_get_content',
post: <?php echo $post->ID; ?>,
}, function( response ) {
$( '#gwsa-content' ).html( response );
} );
} )( jQuery );
</script>
<?php
return ob_get_clean();
}
function ajax_get_content() {
$post_id = rgpost( 'post' );
if( $this->has_access( $post_id ) ) {
$post = get_post( $post_id );
$GLOBALS['post'] = get_post( $post_id );
setup_postdata( $post );
remove_filter( 'the_content', array( $this, 'maybe_hide_the_content' ) );
// use the_content() so we get the content exactly as WP would have originally displayed it
ob_start();
the_content();
$content = ob_get_clean();
} else {
$content = $this->get_requires_submission_message( $post_id );
}
die( $content );
}
function get_requires_submission_message( $post_id ) {
$requires_submission_message = get_post_meta( $post_id, 'gwsa_requires_submission_message', true );
$contains_form_merge_tag = strpos( $requires_submission_message, '{form}' ) !== false;
if( ! $requires_submission_message || $contains_form_merge_tag ) {
$form_ids = $this->get_form_ids( $post_id );
if( ! empty( $form_ids ) ) {
ob_start();
$form = GFAPI::get_form( $form_ids[0] );
require_once( GFCommon::get_base_path() . '/form_display.php' );
GFFormDisplay::print_form_scripts( $form, true );
gravity_form( $form_ids[0], false, false, false, array(), $this->_args['bypass_cache'] );
$form_markup = ob_get_clean();
$requires_submission_message = $contains_form_merge_tag ? str_replace( '{form}', $form_markup, $requires_submission_message ) : $form_markup;
// Replace form's action URL.
if( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
$search = remove_query_arg( 'gf_token' );
$replace = get_permalink( rgpost( 'post' ) );
// get_permalink() defaults to whatever protocol the site url is configured for; we need to be sure
// if the form is being loaded on an https page, that our action url is also https.
if( is_ssl() ) {
$replace = str_replace( 'http://', 'https://', $replace );
}
$requires_submission_message = str_replace( $search, $replace, $requires_submission_message );
}
}
}
if( ! $requires_submission_message ) {
$requires_submission_message = $this->_args['requires_submission_message'];
}
return do_shortcode( $requires_submission_message );
}
function get_requires_submission_redirect( $post_id ) {
return get_post_meta( $post_id, 'gwsa_requires_submission_redirect', true );
}
function has_access( $post_id ) {
if( ! $this->requires_access( $post_id ) ) {
return true;
}
$form_ids = $this->get_form_ids( $post_id );
$submitted_forms = $this->get_submitted_forms();
// if not form-specific and at least one form is submitted, user has access
if( empty( $form_ids ) && ! empty( $submitted_forms ) ) {
return true;
}
// has specifically required form been submitted?
$matching_form_ids = array_intersect( $form_ids, $submitted_forms );
if( ! empty( $matching_form_ids ) ) {
return true;
}
return false;
}
function requires_access( $post_id ) {
return get_post_meta( $post_id, 'gwsa_require_submission', true ) == true;
}
function get_submitted_forms() {
// always check the cookie first; will allow user meta vs cookie to be set per page in the future
$submitted_forms = (array) json_decode( stripslashes( rgar( $_COOKIE, 'gwsa_submitted_forms' ) ) );
// if user meta is enabled, merge forms stored there as well
if( $this->_args['enable_user_meta'] ) {
$user_meta_forms = (array) wp_get_current_user()->get( 'gwsa_submitted_forms' );
$submitted_forms = array_merge( $submitted_forms, $user_meta_forms );
}
return array_filter( $submitted_forms );
}
function add_submitted_form( $form ) {
$submitted_forms = $this->get_submitted_forms();
$form_id = $form['id'];
if( ! in_array( $form_id, $submitted_forms ) && ! headers_sent() ) {
$submitted_forms[] = $form_id;
if( $this->_args['enable_user_meta'] && is_user_logged_in() ) {
update_user_meta( get_current_user_id(), 'gwsa_submitted_forms', $submitted_forms );
} else {
$expiration = $this->_args['is_persistent'] ? strtotime( '+1 year' ) : null;
setcookie( 'gwsa_submitted_forms', json_encode( $submitted_forms ), $expiration, '/' );
}
}
}
function get_form_ids( $post_id ) {
return array_filter( array_map( 'trim', explode( ',', get_post_meta( $post_id, 'gwsa_form_ids', true ) ) ) );
}
}
# Configuration
new GW_Submit_Access();
view raw gw-gravity-forms-submit-to-access.php hosted with ❤ by GitHub

You have a post or page you’d like to protect but you don’t want to require the user to sign up for a user account and you just don’t need a full-blown membership system. All you want to do is collect a few details about the user for your mailing list or CRM.

This plugin provides an easy way to accomplish this. Any post-based content (that includes pages and custom post types) that support custom fields can be locked down. You set a few special custom fields and the Gravity Forms Submit to Access plugin takes care of the rest.

Getting Started

  1. Check requirements

    • Make sure you have Gravity Forms installed and activated.
      • Already have a license? Download Latest Gravity Forms
      • Need a license? Buy Gravity Forms
  2. Install the plugin

    • Click the “Download Code” button above and save the file to your Desktop.
    • Drop the file into your WordPress plugins folder via FTP – or – zip the file up and upload it via WordPress plugin uploader.
  3. Configure the plugin

    • Read on for step-by-step instructions

Locking Down a Page

  1. Navigate to the Edit screen for any post, page, or any custom post type.

  2. Enable “Custom Fields” via the “Screen Options” at the top of the page. There is a good chance they are already enabled.

    gw-submit-to-access-enable-custom-fields
  3. Add a custom field named gwsa_require_submission with a value of 1.

    gw-submit-to-access-gwsa-require-submission
  4. Add a custom field named gwsa_form_ids and set the value to the ID of whichever form the user should submit to gain access to this page.

    gw-submit-to-access-gwsa-form-ids

That’s it! For a complete list of the available options, read on.

Custom Field Options

gw-submit-to-access-custom-field-options
  • gwsa_require_submission (int) (required)

    Add this custom field with a value of 1 to require a Gravity Form to be submitted to gain access.

  • gwsa_form_ids (bool) (optional)

    Add this custom field and set the value to the ID of the form which must be submitted to gain access to this page. If there are multiple forms that can be submitted to gain access, you may include them as a comma-delimited list (i.e. 1,2,3). If any form can be submitted to gain access to this page, do not add this custom field option.

  • gwsa_requires_submission_message (string) (optional)

    Override the default message that is displayed when the user does not have access to view the content of this page.

  • gwsa_requires_submission_redirect (string) (optional)

    Provide a URL to which the user will be redirected if they do not have access to view the content of this page.

Global Parameters

  • requires_submission_message (string) (optional)

    Define the default message that is displayed if the user does not have access to the content. This value will be overridden if a post-specific message is set via the gwsa_requires_submission_message custom field option. Defaults to 'Oops! You do not have access to this page.'.

  • bypass_cache (bool) (optional)

    Enabling this option will allow the script to bypass any page/cookie caching by fetching the post content via AJAX. Defaults to false.

  • loading_message (array) (optional)

    If bypass_cache is enabled, this option allows you to control the loading message which is visible while the post content is being fetched via AJAX.

  • is_persistent (bool) (optional)

    The cookie that stores which forms have been submitted for the visitor is persistent by default. Set this to false to make the cookie session-based.

Any questions?

This is a bare bones plugin. It uses WordPress’ custom fields UI to handle setting the options and advanced configuration should happen in the plugin.

If this proves to be a popular resource, I’ll be happy to enhance it to be even easier to use.

Did this resource help you do something awesome with Gravity Forms? Then you'll absolutely love Gravity Perks; a suite of 29+ essential add-ons for Gravity Forms with support you can count on.

  • View All Perks
  • Buy Gravity Perks

Filed Under: Plugins membership protect content

Comments

  1. Gary Pyne says

    January 4, 2019 at 10:52 am

    Hi David,

    Can this be used to restrict access to a Woocommerce product page?

    Currently it just restricts access to description text.

    Cheers

    Reply
  2. Luzan says

    November 20, 2018 at 6:48 am

    I am not sure if the problem is on my end or the plugin has stopped working. I am usiing Gravity Forms 2.1.3 and Gravity Forms Submit to Access version 1.7, I followed the instruction as above on my publicly published page, but still I am not seeing any message or anything.

    I can see the content of the page.

    Reply
    • David Smith says

      December 1, 2018 at 10:01 am

      Hi Luzan, this is typically a configuration issue. It’s difficult to assess without access to your install. If you’re a Gravity Perks customer, we’ll be happy to provide support via the support form.

  3. Ilya says

    November 13, 2018 at 10:37 am

    Hi, I’ve just installed this plugin and now I can’t access the dashboard or even my login screen, all I get is this message – Authorization Required

    This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn’t understand how to supply the credentials required.

    Reply
    • David Smith says

      November 13, 2018 at 10:41 am

      Hm, not sure. Log in with FTP, remove the plugin, and see if that issue goes away. No one else has reported this issue so it seems to be specific to your configuration.

    • Ilya says

      November 13, 2018 at 11:04 am

      Thanks! this worked. I first tried renaming it to just gw-gravity-forms-submit-to-access2 which I assumed would deactivate it at least but it was still not working. Deleting the folder worked though. Could it be clashing with a security plugin like ithemes? a real shame because I need a plugin that provides a download after a gravity form submission (including Stripe payment), I’ll try and find another solution.

  4. Faisal Yaqoob says

    October 2, 2018 at 9:20 pm

    Hi, First of all. This is brilliant.

    Can we use this with ACF fields. I mean to say if a post has acf fields and can only access after form submission.

    Thanks

    Reply
    • David Smith says

      October 2, 2018 at 10:28 pm

      It depends on how you have your ACF fields configured to be output. If they aren’t output within the_content, this probably won’t work out of the box.

  5. Will says

    September 26, 2018 at 12:55 pm

    So I have tried implementing this and am getting the following problematic behavior:

    I have a page which I have included the requisite custom fields (gwsa_require_submission and gwsa_form_ids) when I go to this page I see the form appear.

    If I submit the form the page content loads.

    If I reload the page the form re-appears. If I open a new tab and navigate to this page the form appears, instead of the page content as I would expect.

    If I go to a secondary page with the same custom field values and the redirect field key/value it redirects instead of the content showing as I would expect.

    When I look at my developer tools I see that a cook (gwsa_submitted_forms) is set with value %5B1%5D.

    Do you (or anyone) have any clue why this is happening?

    Thanks, Will

    Reply
  6. Joe says

    September 11, 2018 at 3:50 am

    Hey Thanks!!! This is an awesome Plugin! I’m asking folks to vote for logo via Gravity Forms… then once they’ve voted I give them a chance to win a prize if they’ll just give us a little more info. I only wanted people who voted for a logo to be given the opportunity to enter the contest. “Submit a Gravity Form to Access Content” was the magic bullet! Much appreciated!

    Reply
    • David Smith says

      September 25, 2018 at 8:22 am

      Glad we could help, Joe!

  7. Rizwan says

    August 31, 2018 at 4:43 am

    Is it possible that i can make the cookie session very small. Once user submit the form and go to restricted page. With in 30 seconds the cookie session expired now if user refresh the restricted page then he again need to fill the form. Is that possible?

    Reply
    • David Smith says

      August 31, 2018 at 7:28 am

      The easiest way to do this would be to replace line 309 of the snippet with this:

      $expiration = time() + 30;

  8. David says

    August 16, 2018 at 7:01 pm

    I’ve added the form to my single post template, but it seems if someone completes the form for any post, they can access all posts.

    Is it possible to collect this data for each post?

    Reply
    • David Smith says

      August 24, 2018 at 10:06 am

      Hi David, this feature is not currently supported. The restriction is not dependent on which post the form is submitted from but which form is submitted. Definitely something we’ll consider for a future version.

  9. Scott Kirkowski says

    August 8, 2018 at 7:31 am

    I’m having a similar issue as David did, and try multiple ways to resolve this. The first way, we set the confirmation as a redirect to same page of the protected content. It just keep having the form reappear, only when we hit the submit form again (without entering any information), would the content appear. The second way, we set the confirmation as a redirect to a new page and had a link back to the protected content page. When they go back, the form still appears and not the content. It is using a child of the Divi theme. Is there something we are missing?

    Reply
    • David Smith says

      August 24, 2018 at 10:11 am

      Hi Scott, hard to say. This snippet is difficult to debug remotely and, unfortunately, we don’t have the throughput to provide hands-on support pro bono; however, if you’re a Gravity Perks customer, we’ll be happy to provide additional support via the support form.

« Older Comments

Leave a Reply Cancel 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.

Categories

  • How To (29)
  • News (20)
  • Plugins (5)
  • Releases (5)
  • Resource (1)
  • Snippets (61)
  • Tip (1)
  • Tutorials (43)
  • Updates (62)

Recent Posts

  • Gravity Wiz Weekly #62
  • Gravity Forms Populate Anything, Public Beta Available!
  • Gravity Wiz Weekly #61
  • Gravity Wiz Weekly #60
  • Gravity Wiz Weekly #59

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Copyright © 2019 · Powered by WordPress · Gravity Wiz LLC · Log out

  • Support
  • Affiliates
  • About
  • Sitemap
  • Gravity Perks
    ▼
    • Gravity Perks
    • Tutorials & Snippets
    • About
  • Support
    ▼
    • Documentation
    • Support
    • Account