• I was working on a project that required knowing the post ID of the current post being viewed and I was unable to find a good answer on how to get that post ID using JavaScript.

    I would love to think that this will work on all WordPress installs, but I cannot make that guarantee. However, I did test it on a few of the WordPress Showcase websites (Adobe, Sony, and SiriusXM Canada) and it worked like a charm. For this to work, your <body> tag MUST have the class “postid-###” (where ### is the ID).

    I am posting 2 flavors of this, one for raw JavaScript and one for jQuery. For this, there is really no advantage of using jQuery.

    JavaScript:
    var post_id = parseInt( ( document.body.className.match( /(?:^|\s)postid-([0-9]+)(?:\s|$)/ ) || [ 0, 0 ] )[1] );

    jQuery (1.6 or later):
    var post_id = parseInt( ( jQuery( 'body' ).prop( 'class' ).match( /(?:^|\s)postid-([0-9]+)(?:\s|$)/ ) || [ 0, 0 ] )[1] );

    jQuery (1.5.x or earlier):
    var post_id = parseInt( ( jQuery( 'body' ).attr( 'class' ).match( /(?:^|\s)postid-([0-9]+)(?:\s|$)/ ) || [ 0, 0 ] )[1] );

    If the post ID was able to be found, post_id will now contain it. If not, post_id will be 0.

    If anyone has any improvements to be made to this, by all means, please do not hesitate!

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Thanks for sharing! Another possibility would be to have PHP output a script block where $post->ID is assigned to the javascript var:
    echo "<script> var post_id = {$post->ID}; </script>";

    This of course comes with its own set of issues, but could work in some cases.

Viewing 1 replies (of 1 total)
  • The topic ‘Get Post ID from Body Class with JavaScript or jQuery’ is closed to new replies.