4

I'm trying to echo the post ID in a post Javascript and not having any luck.

var post_id = '123';  // works fine

var post_id = '<?php global $post; echo $post->ID; ?>';  // echos 'ID; ?>'

var post_id = '<?php echo $post->ID;?>';  // echos 'ID; ?>'

Is there a correct way to echo the post ID?

2
  • Are you doing it outside loop or inside.? And also you can use the second method to echo it. But remember if you put it inside single quotes than it Wil consider as a string. You Need to parse it before using it
    – Kvvaradha
    Dec 15, 2015 at 1:00
  • Did you check get_queried_object_id() or get_the_ID()?
    – jgraup
    Dec 15, 2015 at 1:02

7 Answers 7

13

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.

6

It is available in the post_ID hidden field for both published and new posts. You can get it by using this simple jQuery code.

jQuery("#post_ID").val()
1
  • 4
    This isn't always available, and can't be relied on. The hidden input with post_ID is added in the editor and not the front end, so it's not available to use in a theme. As long as you're aware of the limitations, this may be totally fine. Mar 7, 2018 at 17:50
4

I use this -

document.querySelector('.status-publish').getAttribute('id');

This gives you post-xxx where xxx is the post number. You can then replace post- with an empty string.

var id = document.querySelector('.status-publish').getAttribute('id').replace("post-", "");
1
  • This is brilliant. Thanks!
    – ronnefeldt
    Feb 22 at 14:23
2

Ok, got it. Maybe this'll help someone. In theme functions.php:

function pid() {

global $current_screen;
$type = $current_screen->post_type;

    ?>
    <script type="text/javascript">
    var post_id = '<?php global $post; echo $post->ID; ?>';
    </script>
    <?php

} 
add_action('wp_head','pid');
2
  • I would remove the $type = $current_screen->post_type;
    – talsibony
    Jan 9, 2018 at 17:11
  • I would generally avoid this method. Writing JS inside of php is generally bad practice and this particular method creates render blocking script. I suggest a solution midway between the suggestions. Assuming you're using a theme like the OP, you can easily add a hidden input in HTML and pass the post id by using get_the_ID(). (Inside of your template files, or it could be added to header.php) Once you have the hidden input, (though it could honestly be any DOM element), it's easily called from JQuery. This method allows for securely checking permissions and avoids render blocking. May 4, 2019 at 18:49
1

to frontend postID = jQuery('article').attr('id').slice(5);

to backend post_ID = jQuery('#post_ID').val();

1
  • The front-end solution is a very theme-dependant approach. Jun 15, 2020 at 10:11
1

NB. As of WP 4.5 it is recommended to use wp_add_inline_script(), rather than wp_localize_script() - the later being intended for localization.

See: wp_localize_script() > More Info

wp_add_inline_script()

0

On the post edit screens when Gutenberg is enabled, you may use a JS variable set by the wp.media object.

wp.media.view.settings.post.id,

On the front end, the best approach was already outlined above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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