WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

how do you set the current post ID as a JS variable with localize_script? It seems like the $post variable isn't availible in the functions.php file. When is it created? Do i have to add localize script to a hook? Which?

share|improve this question
up vote 4 down vote accepted

You should declare global $post; before attempting to access this variable, but to answer your question regarding when it is created, the 'wp' action hook is the safest bet.

As such I'd suggest the following in your functions.php file as a simple solution

function my_localize_post_id(){
   global $post;
    wp_register_script( 'your_script'... /** other parameters required here **/ );
    wp_localize_script( 'your_script', 'the_name_for_your_js_object' , array( 'post_id'=>$post->ID ) );

add_action( 'wp', 'my_localize_post_id' );
share|improve this answer
Yes, I know I should use global. I was trying to run localize script directly in the functions file. But adding it to the wp hook worked great. Thanks! – John Oct 17 '12 at 16:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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