问题
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.
回答1:
Use attributes:
<body data-post-id="<?php echo $thePostID?>">
You can then write
var postId = document.body.getAttribute('data-post-id');
回答2:
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.
回答3:
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);
});
来源:https://stackoverflow.com/questions/16241140/how-can-i-avoid-this-inline-javascript