I have a wp_localize_script() function in my functions.php where I need to push the current post ID of the current post to a jQuery file. So I was wondering how you can get the current post ID of a post in my functions.php.

These are both not working:

global $post;
$post_id = $post->ID;

global $wp_query;
$post_id = $wp_query->get_queried_object_id();

If you hook your localize script function to wp_enqueue_scripts, then you will have access to the global $post variable. As long as you pick a hook at or after 'wp' you should have access to the global $post.

add_action('wp_enqueue_scripts', 'YOUR_NAME_scripts'); 

function YOUR_NAME_scripts() {


            global $post;
            $params = array(
                'site_url' => site_url(),
                'admin_ajax_url' => admin_url('admin-ajax.php'),
                'post_id' => $post->ID

            wp_localize_script( 'jquery', 'YOUR_NAME', $params );

  • Is there any other workaround, as a standalone function for example, instead of inside wp_enqueue_scripts? – Manolis Sep 17 '14 at 13:04
  • Yes, just hook into wp_head and echo script tags with var post_id = <?php echo $post->ID;?>; Just make sure to use global $post; first. Or echo your script tags anywhere in the Page/Post Template if you really want. – Douglas.Sesar Sep 17 '14 at 15:44

protected by Community Feb 14 '18 at 0:02

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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