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

11 Answers 11

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
  • 5
    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, 2023 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
2

Maybe you need it in PHP but here's a pure javascript solution... though you're at the mercy of WordPress keeping the "post-XXX" class in the body.

function getWordPressPostId() {
    let postID = null;
    try {
        document.getElementsByTagName("body")[0].classList.forEach((cls) => {
            if(cls.startsWith("postid-")) {
                postID = cls.split("-")[1];
            }
        });
    } catch(exc) {
        // ... handle exception
    }
    return postID;
}
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()

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
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.

0

I'm using document.getElementById('cdp-current-post-id').value in WordPress 6.4

1
  • Uncaught TypeError: document.getElementById(...) is null
    – Fanky
    Mar 25 at 12:26
0

To retrieve the current post ID in JS within a WP environment, you typically need to pass the post ID from PHP to JS using wp_localize_script() or directly embed it in the HTML markup.

First, enqueue your JS file in your theme's functions.php file

function enqueue_custom_script() {
    // Enqueue your JavaScript file
    wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '', true);
    
    // Pass the post ID to the JavaScript file
    global $post;
    wp_localize_script('custom-script', 'post_id_object', array('post_id' => $post->ID));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');

custom-script.js file, you can access the post ID variable like

// Access the post ID variable passed from PHP
var post_id = post_id_object.post_id;
console.log(post_id); // Output the post ID to the browser console
0

If you mean on the frontend, here's my oneliner for striping the id from the body's class:

var postid = $("body")[0].className.match(/postid-\d+/)[0].split("-")[1];

No need for PHP so you can keep your js scripts separate.

Your Answer

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

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