I have a button within a post which a user can click. Once clicked, an AJAX call is made.

My question is, within my PHP AJAX helper function (located in my theme's function.php) how can I retrieve, for instance, the ID of the post that the request was sent from.

I can get the ID from the markup and pass it in the AJAX call but it seems messy, i.e.

<article id="post-12">
<!-- article content -->

// JS
var postID = $("article").attr("id");

Is there a better way? Some kind of global that is accessible perhaps?


Use wp_localize_script() to declare globals.


wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

You could store your query results there and access them later.

  • The issue there is that the variable is being stored in the mark-up, meaning that anyone that knows how to use firebug can modify the variable and send bogus requests to my helper function.
    – aprea
    Nov 2 '11 at 22:05
  • @aprea You can a) use a nonce within localize script and check this in the post which you then check back in your cb fn and b) you can assign anything (but a more dim. js-array) to the localized object.
    – kaiser
    Feb 4 '12 at 3:28
  • @kaiser nonce only makes sense if users are registered.
    – Mamaduka
    Mar 11 '12 at 9:52
  • @aprea You'll have to validate your result anyway.
    – kaiser
    Mar 11 '12 at 14:36

If this is within the loop, you can use the_ID() or get_the_ID() and pass the value. I don't see how a helper function can know what the post is unless you tell it explicitly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.