Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

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:

object_name.my_meta
share|improve this answer
3  
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. –  chrisguitarguy Jan 18 '13 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 '13 at 20:54
    
AJAX. –  chrisguitarguy Jan 18 '13 at 20:59
    
You are probably right, but I am js newbe so an example would be useful. –  HoGo Jan 18 '13 at 21:03
add comment

Your Answer

 
discard

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.