Get post meta in enqueued js file

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?

Related posts

Leave a Reply

1 comment

  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:

    object_name.my_meta