How can I avoid this inline Javascript?

2019-07-20 03:43发布

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.

3条回答
混吃等死
2楼-- · 2019-07-20 04:27

Use attributes:

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

You can then write

var postId = document.body.getAttribute('data-post-id');
查看更多
看我几分像从前
3楼-- · 2019-07-20 04:29

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.

查看更多
家丑人穷心不美
4楼-- · 2019-07-20 04:38

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);
});
查看更多
登录 后发表回答