That obviously won’t work since you can’t get the ID of the post by doing PHP calls in a javascript code. By the way, the short PHP tag should never be used due to conflicts. You should used the full <?php
tag.
Now, about your problem. What you need to pass the ID is a localization. Include your script in a js file, and enqueue it using this piece of code:
add_action( 'wp_enqueue_scripts', 'some_function' );
function some_function(){
wp_enqueue_script( 'some-handler', 'FULL URL HERE', array( 'jquery' ) );
}
Now, to pass the ID to the script, localize the post’s ID by extending your code to this:
add_action( 'wp_enqueue_scripts', 'some_function' );
function some_function(){
// Enqueue our JS file
wp_enqueue_script( 'some-handler', 'FULL URL HERE', array( 'jquery' ) );
// If we are on a single post, add the post's ID
if ( is_single() ){
$localization = array(
'post_id' => get_the_ID(),
);
wp_localize_script( 'some-handler', 'localized_object', $localization );
}
}
We’re half way done. At this point, you can access your post’s ID directly in your JS file:
(function($){
function popModal() {
window.alert("Your book is overdue.");
}
var hash = window.location.hash;
if (hash.substring(1) == 'post-' + localized_object.post_id ) {
popModal();
}
})(jQuery);
Pretty cool stuff, ha?