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 August 22, 2019 | Written by David Smith 292 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: http://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.

  • enable_user_meta (bool) (optional)

    Set this to true to save submitted forms in the user meta rather than a cookie. Only works for logged-in users.

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 32+ 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. Carl says

    November 25, 2020 at 3:59 am

    Hi! Thanks for providing the plugin!

    I have set up the custom fields on my custom post type after form submission it will just redirect to the restriction message so they still can’t access the protected content.

    Reply
    • Samuel Bassah says

      November 25, 2020 at 6:59 am

      Hi Carl,

      If you already have custom fields parameters set up correctly as described in the tutorial above, try clearing the cache and see if that resolves the issue. You could also run a theme/plugin conflict test to check if another plugin is causing this issue.

      In case this doesn’t work for you, then we may have to log in to your site to check the setup and troubleshoot the issue there. So if you have a Gravity Perks license, you can reach us via our support form so we dig into this.

      Best,

  2. Barak says

    November 25, 2020 at 2:43 am

    Do you have any videos? I did everything that is written here but still, nothing works

    Reply
  3. Kenneth Kanyi says

    November 17, 2020 at 1:43 pm

    Hi! Thanks for providing the plugin!!!

    Are there any known compatibility issues with Elementor Website Builder?

    Once I add the custom fields, save the page, I can’t edit the page (or the fields) anymore. I also get this error “The editor has encountered an unexpected error.”

    Thanks for your help,

    Ken

    Reply
    • Samuel Bassah says

      November 18, 2020 at 6:53 am

      Hi Kenneth,

      The snippet shouldn’t cause any issue with Elementor. It could be with the way you’re creating the custom fields. You may want to check out this article on how to add custom fields in Elementor. If you have a Gravity Perks License and you’re still having issues, you can send us a message via our support form so that we can dig into this.

      Best,

    • Grant Bivens says

      December 16, 2020 at 2:51 pm

      This is the same behavior I see when working with Divi Page Builder. The issue is you haven’t submitted the form and set a cookie in your browser giving you access to the page you are trying to edit. Just go submit your access form to set a cookie then return to edit your locked content page. The problem lies in that Elementor (as well as Divi) is loading the full page and not just the WordPress text editor thus getting blocked by the submit to access perk.

« 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 (64)
  • News (21)
  • Plugins (14)
  • Releases (7)
  • Resource (3)
  • Snippets (58)
  • Tutorials (57)
  • Updates (104)

Recent Posts

  • How to Send a Follow-Up and Pre-Fill Information
  • How to Update Posts with Gravity Forms
  • Gravity Wiz Weekly #104
  • The Complete Guide to Using Gravity Forms With Zapier
  • Gravity Wiz Weekly #103

Meta

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

Copyright © 2021 · Powered by WordPress · Gravity Wiz LLC

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