I am writing a plugin in which I have a js file. I enqueue it with wp_enqueue_script. In this file I have some functions. The functions are triggered by an onclick event of a button. The button is located on edit post page. Now I need those functions to get post meta of the edited post, modify and save.

Does anyone have any idea how to do it?

1 Answer 1


You can send variables to your script with wp_localize_script:

wp_enqueue_script( 'some_handle' );

global $post;
$my_meta = get_post_meta( $post->ID, 'my_meta', true );

$array = array( 
    'my_meta' => $my_meta

wp_localize_script( 'some_handle', 'object_name', $array );

You can then use the var in your script like:

  • 4
    Might want to check is_singular first before using the global post object, or it won't work like you expect. Also, get_queried_object_id: $meta = get_post_meta(get_queried_object_id(), 'my_meta', true);. No need for global $post. Jan 18, 2013 at 20:46
  • This is a very good idea, but I need then to modify the variable in js file and update it. Any idea how?
    – HoGo
    Jan 18, 2013 at 20:54
  • AJAX. Jan 18, 2013 at 20:59
  • You are probably right, but I am js newbe so an example would be useful.
    – HoGo
    Jan 18, 2013 at 21:03

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.