Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress Form action doesn't work with AMP

I'm trying to use AMP with form action in wordpress. I'm using action-xhr with POST method.

When I submit form, it gives error

  • Response must contain the AMP-Access-Control-Allow-Source-Origin header
  • Form submission failed: Error: Response must contain the AMP-Access-Control-Allow-Source-Origin header​​​

Even tried adding header as shown below

header("AMP-Access-Control-Allow-Source-Origin: https://www.demo.com");

still the issue persist. Any suggestions?

I am using wordpress version 5.0.3

like image 491
Ankit Kumbhar Avatar asked May 28 '26 19:05

Ankit Kumbhar


1 Answers

You can set headers with your .htaccess file.

Header set Access-Control-Allow-Origin 'https://cdn.ampproject.org​'
Header set AMP-Access-Control-Allow-Source-Origin 'https://your-domain.com'

Or there is simple example for you ;

function amp_comment_submit(){
  $comment = wp_handle_comment_submission( wp_unslash( $_POST ) );
  if ( is_wp_error( $comment ) ) {
    $data = intval( $comment->get_error_data() );
    if ( ! empty( $data ) ) {
      status_header(500);
      wp_send_json(array('msg' => $comment->get_error_message(),
                        'response' => $data, 
                        'back_link' => true ));
    }
  }
  else {
    @header('AMP-Redirect-To: '. get_permalink($_POST['comment_post_ID']));
    @header('AMP-Access-Control-Allow-Source-Origin: ' . $_REQUEST['__amp_source_origin'] );
    wp_send_json(array('success' => true));
  }
}
add_action('wp_ajax_amp_comment_submit', 'amp_comment_submit');
add_action('wp_ajax_nopriv_amp_comment_submit', 'amp_comment_submit');

For more : https://medium.com/@surajair/creating-comment-form-on-amp-pages-in-wordpress-9dd675ba383b

like image 116
Fatih Toprak Avatar answered May 30 '26 14:05

Fatih Toprak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!