简体   繁体   English

如何将JavaScript添加到WordPress PHP文件?

[英]How to add JavaScript to WordPress PHP file?

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. 我想从WordPress PHP文件的根文件夹中引用JavaScript文件,但是在加载页面时,JavaScript被忽略了。 Is there a WordPress restriction on referencing .js files? WordPress对引用.js文件有限制吗? Am I not correctly referencing JavaScript for PHP? 我没有正确引用PHP的JavaScript吗?

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>

For jQuery I use this technique Loading The Latest Version of jQuery in WordPress 对于jQuery,我使用此技术在WordPress中加载jQuery的最新版本

Basically you use wp_enqueue_script function in functions.php . 基本上你在functions.php中使用wp_enqueue_script 函数

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. 对于我想简单地将它们添加到模板文件中并且不想打扰wp_enqueue_script 脚本 ,我将它们放在主题文件夹中创建的脚本文件夹中。 I add All custom added .js scripts there. 我在那里添加所有自定义添加的.js脚本。

Then in the template file I use the code like this: 然后在模板文件中我使用如下代码:

<script type="text/javascript" src="<?=get_template_directory_uri();?>/scripts/markers.js"></script>

Wordpress has its own method to add js or css files. WordPress有自己的添加js或css文件的方法。

<?php
function my_scripts_loader() {
    wp_enqueue_script( 'my-js', 'filename.js', false );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_loader' );
?>

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. WordPress有多种方法来包含文件,我本人在早期就使用WordPress,但那时我不得不使用WordPress函数来调用路径。

Example: <script src="<?php echo bloginfo('template_directory'); ?>/files/js/jquery.js" type="text/javascript"></script> //add echo 示例: <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. 你可能想要var_dump bloginfo('template_directory')并从那里开始工作。

Put your files folder to your wordpress theme which you are curently useing after that just need to 将您的文件文件夹放入您的wordpress主题,然后您只需要使用它

include the path on header.php file like 包括header.php文件中的路径,如

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

hope this will help you .... 希望这个能对您有所帮助 ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM