admin管理员组

文章数量:1126298

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 .-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
});

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
});
Share Improve this question asked Feb 13, 2024 at 14:56 GoSSDHostingGoSSDHosting 112 bronze badges 3
  • 1 Here's how the nonce is set in wp_default_scripts. I guess your AMP page doesn't use the default scripts? – Rup Commented Feb 13, 2024 at 15:36
  • this is a php script, looking for javascript for AMP – GoSSDHosting Commented Feb 13, 2024 at 19:03
  • 1 WordPress Nonce is set by PHP and then passed across to the JS. – Tony Djukic Commented Feb 15, 2024 at 15:19
Add a comment  | 

1 Answer 1

Reset to default 0

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

本文标签: Wordpress Rest API Post request from AMP