1

I am trying to figure out how to send a post request to a WP Rest API function on an AMP Page.

The endpoint requires 2 fields, post_id & nonce.

/wp-json/wordpress-popular-posts/v2/views/[post_id] as per the guide on https://github.com/cabrerahector/wordpress-popular-posts/wiki/8.-REST-API-Endpoints

Now the task here is how to send a request from the AMP page to this endpoint. My theme offers the ability to add custom html/javascript/CSS code to the AMP page.

But how can we get the nonce and post_id dynamically using Javascript?

Can the below code help me solve the issue?

$.ajax({ url: foo, method: "POST", beforeSend: function(xhr) { xhr.setRequestHeader("X-WP-Nonce", wpApiSettings.nonce); }, data: { "foo": bar } }).done(function(response) { // your custom code }); 
3
  • 1
    Here's how the nonce is set in wp_default_scripts. I guess your AMP page doesn't use the default scripts? Commented Feb 13, 2024 at 15:36
  • this is a php script, looking for javascript for AMP Commented Feb 13, 2024 at 19:03
  • 1
    WordPress Nonce is set by PHP and then passed across to the JS. Commented Feb 15, 2024 at 15:19

1 Answer 1

0

You need to localize the nonce here's how: https://developer.wordpress.org/reference/functions/wp_localize_script/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.