How to add JavaScript to WordPress PHP file?

2019-07-20 16:04发布

I would like to reference JavaScript files from my root folder in a WordPress PHP file, however when I load the page, the JavaScript is being ignored. Is there a WordPress restriction on referencing .js files? Am I not correctly referencing JavaScript for PHP?

This is what I wrote (which does not work):

<?php wp_footer(); ?>
<script src="/files/js/jquery.js" type="text/javascript"></script>
<script src="/files/js/jquery.cycle.js" type="text/javascript"></script>
</body>
</html>

4条回答
聊天终结者
2楼-- · 2019-07-20 16:10

Wordpress has its own method to add js or css files.

<?php
function my_scripts_loader() {
    wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_loader' );
?>
查看更多
虎瘦雄心在
3楼-- · 2019-07-20 16:25

WordPress got a various number of ways to include file, I myself have worked with WordPress in the early days, back then I had to call the path with a WordPress function.

Example: <script src="<?php echo bloginfo('template_directory'); ?>/files/js/jquery.js" type="text/javascript"></script> //add echo

You might want to var_dump the bloginfo('template_directory') and work your way from there.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-07-20 16:27

For jQuery I use this technique Loading The Latest Version of jQuery in WordPress

Basically you use wp_enqueue_script function in functions.php.

For scripts where I want to simply add them in the template files and don't want to bother with wp_enqueue_script, I put them in scripts folder that was created in the theme folder. I add All custom added .js scripts there.

Then in the template file I use the code like this:

<script type="text/javascript" src="<?=get_template_directory_uri();?>/scripts/markers.js"></script>
查看更多
迷人小祖宗
5楼-- · 2019-07-20 16:29

Put your files folder to your wordpress theme which you are curently useing after that just need to

include the path on header.php file like

<script src="<?php bloginfo('template_directory'); ?>/files/js/jquery-min.js" type="text/javascript"></script>

hope this will help you ....

查看更多
登录 后发表回答