Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AMP shim support for Gravity Forms submissions
<?php
/**
* AMP Gravity Forms Submission Shim plugin bootstrap.
*
* @package Google\AMP_Gravity_Forms_Submission_Shim
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2020 Google Inc.
*
* @wordpress-plugin
* Plugin Name: AMP Gravity Forms Submission Shim
* Plugin URI: https://gist.github.com/westonruter/b2554073461707a88057bb86b6b603d6
* Description: Plugin which shims AMP compatibility for Gravity Forms by fixing redirection upon submission and ensuring HTML5 form validation is used for required fields.
* Version: 0.1.4
* Author: Weston Ruter
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
* Gist Plugin URI: https://gist.github.com/westonruter/b2554073461707a88057bb86b6b603d6
*/
// Shim support for Gravity Form submissions on AMP pages.
add_action( 'gform_post_submission', function() {
$location = null;
foreach ( headers_list() as $header ) {
if ( preg_match( '/^Location:\s*(.+)/i', $header, $matches ) ) {
$location = $matches[1];
break;
}
}
if ( $location ) {
header_remove( 'Location' );
header( "AMP-Redirect-To: $location" );
header( 'AMP-Access-Control-Allow-Source-Origin: ' . home_url() );
header( 'Access-Control-Expose-Headers: AMP-Redirect-To, AMP-Access-Control-Allow-Source-Origin' );
wp_send_json(
[
'message' => __( 'Redirecting…', 'amp' ),
'redirecting' => true, // Make sure that the submit-success doesn't get styled as success since redirection _could_ be to error page.
],
200
);
}
} );
// Use client-side validation UI instead of showing validation errors after page reload. Props Rahul Bansal at rtCamp.
add_filter( 'gform_field_content', function( $content, $field ) {
if ( $field->isRequired ) {
return str_replace( 'aria-required=', 'required=', $content );
}
return $content;
}, 10, 2 );
@westonruter

This comment has been minimized.

Copy link
Owner Author

@westonruter westonruter commented Apr 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.