Get the current post ID as a variable in Javascript

You can pass variables to javascript using wp_localize_script function:
https://codex.wordpress.org/Function_Reference/wp_localize_script

Add the following to functions.php

if(!function_exists('load_my_script')){
    function load_my_script() {
        global $post;
        $deps = array('jquery');
        $version= '1.0'; 
        $in_footer = true;
        wp_enqueue_script('my-script', get_stylesheet_directory_uri() . '/js/my-script.js', $deps, $version, $in_footer);
        wp_localize_script('my-script', 'my_script_vars', array(
                'postID' => $post->ID
            )
        );
    }
}
add_action('wp_enqueue_scripts', 'load_my_script');

And your js file (theme-name/js/my-script.js):

jQuery(document).ready(function($) {
        alert( my_script_vars.postID );
});

Note:

If you are trying to pass integers you will need to call the JavaScript parseInt() function.

Leave a Comment