2

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.

asked Apr 26, 2013 at 16:31

3 Answers 3

5

Use attributes:

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

You can then write

var postId = document.body.getAttribute('data-post-id');
answered Apr 26, 2013 at 16:32
Sign up to request clarification or add additional context in comments.

3 Comments

and since in WP normally there's jQuery you could also use var postID = $(body).attr('data-post-id');
yes @Paolo Casciello, I am totally agreeing with you. thanks again.
@PaoloCasciello: $(body).data('post-id')
1

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.

answered Apr 26, 2013 at 16:35

5 Comments

Thank you nick for your help, appreciated
Immediately invoked function expression within a callback function?
@Rick true not necessary but keeps it seperate from other things in onload.
I come back here after 2 years to note Rick Viscomi comment. For people reading, this is working but not following best practice: use named functions in jQuery dom ready callback and do not mix php with markup and/or javascript. Slaks answer is the most correct one
is not anything written inside <script> tag is considered inline scripting?
0

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);
});
answered Jul 14, 2015 at 5:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.