Last active
September 5, 2024 01:58
-
-
Save westonruter/b2554073461707a88057bb86b6b603d6 to your computer and use it in GitHub Desktop.
AMP shim support for Gravity Forms submissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation instructions: https://gist.github.com/westonruter/6110fbc4bef0c4b8c021a112012f7e9c