简体   繁体   中英

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. 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>

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>

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' );
?>

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.

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 ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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