Question

I have a wordpress site. Under single.php, I have the following body tag

  <body <?php body_class(); ?>  onLoad="func(<?php echo $thePostID?>);" >

Reading articles on the web made me convinced of avoiding inline CSS and inline javascipt. So I made a restructuring of my site so that styles and scripts are contained now in external files. Except for this line of code since it really need the post id and I dont know how can I retrieve it outside of single.php.

Your usual help is appreciated.

Was it helpful?

Solution

Use attributes:

<body data-post-id="<?php echo $thePostID?>">

You can then write

var postId = document.body.getAttribute('data-post-id');

OTHER TIPS

Just call it in a script, or document.onload...

<script>
 $(document).ready(function(){
 (function(){
    <?php echo $thePostID?; ?>
 })();
 });

</script>

It's totally acceptable to write javascript inside script tags. Even though it's not in an external file, it's outside your html.

i would recommend using wp_localize_script

function theme_localize_post_id(){
   global $post;
    wp_register_script( 'your_script',... );
    wp_localize_script( 'your_script', 'the_name_for_your_js_object' , array( 'post_id'=>$post->ID ) );
}

add_action( 'wp', 'theme_localize_post_id' );

then in your script simple use.

$(document).ready(function(){
  functionName(post_id);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top