Using wp_enqueue in Wordpress - javascript

I turn to this awesome community , after days of trying to fix this bug, my problem is really simple, but it has got to me. I am trying to enqueue a Java script to my Theme my login Plugin while using the evolve theme.
here is the code snippet that does that, and i used the global function to check if the function is being loaded , and it is not being loaded. 'a' does not change to true.
For some reason it looks like 'wp_enqueue_scripts is not working. I have tried to also add wp_head() with no luck.
<?php
$GLOBALS['a'] = 'false';
add_action( 'wp_enqueue_scripts', 'load_location' );
function load_location() {
$GLOBALS['a'] = 'true';
wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
wp_enqueue_script('load_location_test');
}
?>
<?php echo $GLOBALS['a'] ?>;
Thanks in advice
The link is http://www.meetntrain.com/register

So, for your enqueue to work, you need to add the code in your functions.php file or in your plugin.
add_action( 'wp_enqueue_scripts', 'load_location' );
function load_location() {
wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
wp_enqueue_script('load_location_test');
}
This will add the JS file to all your pages. If you want to target a specific page, you can either do it via JavaScript or directly in your PHP file.
If your theme uses body_class(), you can target that specific page by the class. You should then wrap your JS like:
if( $('body.classUsed').length ){
// Your JS code here
}
Note that the file will still be enqueued all the time. Alternately, if you want to add the JS file only to a specified page, you can wrap it in an is_page() condition:
add_action( 'wp_enqueue_scripts', 'load_location' );
function load_location() {
if( is_page('your-page') ){
wp_register_script('load_location_test',get_template_directory_uri().'/load_location.js', array('jquery'),'1.1',true);
wp_enqueue_script('load_location_test');
}
}

You should look at the docs or at the files of other plugins, walkthroughs online, etc, to understand more. wp_enqueue_scripts is a hook you're using to load your Javascript, and you have the basic right idea, but try something a little more like this inside your functions.php:
function my_custom_scripts() {
wp_register_script( 'custom-js', 'js/custom.js' );
wp_enqueue_script( 'custom-js', 'js/custom.js', false );
}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts' );
Change out the "js/custom.js" for wherever your directory has your JS file.
Another option, if this is proving too tough, is to put a direct link to the JS file at the bottom of your footer.php. Like <script src="/path/to/my/file.js"></script>.
I do find the enqueuing scripts thing a little weird sometimes though, hope this helps you get it figured out.

Related

Add Jquery File to Wordpress [duplicate]

I read the Codex and a few blog posts about using jQuery in WordPress, and its very frustrating. I've got as far as loading jQuery in functions.php file, but all of the guides out there are crappy because they assume you already have a ton of WordPress experience. For instance, they say that now that I'm loading jQuery through the functions.php file, now all I have to do is load my jQuery.
How exactly do I do this? What files, specifically, do I add code to? How exactly do I add it for a single WordPress page?
I know what you mean about the tutorials. Here's how I do it:
First you need to write your script. In your theme folder create a folder called something like 'js'. Create a file in that folder for your javascript. E.g. your-script.js. Add your jQuery script to that file (you don't need <script> tags in a .js file).
Here is an example of how your jQuery script (in wp-content/themes/your-theme/js/your-scrript.js) might look:
jQuery(document).ready(function($) {
$('#nav a').last().addClass('last');
})
Notice that I use jQuery and not $ at the start of the function.
Ok, now open your theme's functions.php file. You'll want to use the wp_enqueue_script() function so that you can add your script whilst also telling WordPress that it relies on jQuery. Here's how to do that:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
Assuming that your theme has wp_head and wp_footer in the right places, this should work. Let me know if you need any more help.
WordPress questions can be asked over at WordPress Answers.
After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:
Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).
Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).
Make sure your custom jQuery .js looks like this:
(function($) {
$(document).ready(function() {
$('.your-class').addClass('do-my-bidding');
})
})(jQuery);
Go to the theme's directory, open up functions.php
Add some code near the top that looks like this:
//this goes in functions.php near the top
function my_scripts_method() {
// register your script location, dependencies and version
wp_register_script('custom_script',
get_template_directory_uri() . '/custom_js/jquery_test.js',
array('jquery'),
'1.0' );
// enqueue the script
wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
Check out your site to make sure it works!
If you use wordpress child theme for add scripts to your theme, you should change the get_template_directory_uri function to get_stylesheet_directory_uri, for example :
Parent Theme :
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script(
'parent-theme-script',
get_template_directory_uri() . '/js/your-script.js',
array('jquery')
);
wp_enqueue_script('parent-theme-script');
}
Child Theme :
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script(
'child-theme-script',
get_stylesheet_directory_uri() . '/js/your-script.js',
array('jquery')
);
wp_enqueue_script('child-theme-script');
}
get_template_directory_uri : /your-site/wp-content/themes/parent-theme
get_stylesheet_directory_uri : /your-site/wp-content/themes/child-theme
You can add jQuery or javascript in theme's function.php file.
The code is as below :
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your_script_name', // your script unique name
get_template_directory_uri().'/js/your-script.js', //script file location
array('jquery') //lists the scripts upon which your script depends
);
}
For more detail visit this tutorial : http://www.codecanal.com/add-simple-jquery-script-wordpress/
Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever. You just need to make sure the path is correct. I suggest using something like this (assuming you are in your theme's directory).
<script type="javascript" href="<?php echo get_template_directory_uri();?>/your-file.js"></script>
A good practice is to include this right before the closing body tag or at least just prior to your footer. You can also use php includes, or several other methods of pulling this file in.
<script type="javascript"><?php include('your-file.js');?></script>
The solutions I've seen are from the perspective of adding javascript features to a theme. However, the OP asked, specifically, "How exactly do I add it for a single WordPress page?" This sounds like it might be how I use javascript in my Wordpress blog, where individual posts may have different javascript-powered "widgets". For instance, a post might let the user change variables (sliders, checkboxes, text input fields), and plots or lists the results.
Starting from the JavaScript perspective:
Write your JavaScript functions in a separate “.js” file
Don’t even think about including significant JavaScript in your post’s html—create a JavaScript file, or files, with your code.
Interface your JavaScript with your post's html
If your JavaScript widget interacts with html controls and fields, you’ll need to understand how to query and set those elements from JavaScript, and also how to let UI elements call your JavaScript functions. Here are a couple of examples; first, from JavaScript:
var val = document.getElementById(“AM_Freq_A_3”).value;
And from html:
<input type="range" id="AM_Freq_A_3" class="freqSlider" min="0" max="1000" value="0" oninput='sliderChanged_AM_widget(this);'/>
Use jQuery to call your JavaScript widget’s initialization function
Add this to your .js file, using the name of your function that configures and draws your JavaScript widget when the page is ready for it:
jQuery(document).ready(function( $ ) {
your_init_function();
});
In your post’s html code, load the scripts needed for your post
In the Wordpress code editor, I typically specify the scripts at the end of the post. For instance, I have a scripts folder in my main directory. Inside I have a utilities directory with common JavaScript that some of my posts may share—in this case some of my own math utility function and the flotr2 plotting library. I find it more convenient to group the post-specific JavaScript in another directory, with subdirectories based on date instead of using the media manager, for instance.
<script type="text/javascript" src="/scripts/utils/flotr2.min.js"></script>
<script type="text/javascript" src="/scripts/utils/math.min.js"></script>
<script type="text/javascript" src="/scripts/widgets/20161207/FreqRes.js"></script>
Enqueue jQuery
Wordpress registers jQuery, but it isn’t available unless you tell Wordpress you need it, by enqueuing it. If you don’t, the jQuery command will fail. Many sources tell you how to add this command to your functions.php, but assume you know some other important details.
First, it’s a bad idea to edit a theme—any future update of the theme will wipe out your changes. Make a child theme. Here’s how:
https://developer.wordpress.org/themes/advanced-topics/child-themes/
The child’s functions.php file does not override the parent theme’s file of the same name, it adds to it. The child-themes tutorial suggest how to enqueue the parent and child style.css file. We can simply add another line to that function to also enqueue jQuery. Here's my entire functions.php file for the child theme:
<?php
add_action( 'wp_enqueue_scripts', 'earlevel_scripts_enqueue' );
function earlevel_scripts_enqueue() {
// styles
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
// posts with js widgets need jquery
wp_enqueue_script('jquery');
}
**#Method 1:**Try to put your jquery code in a separate js file.
Now register that script in functions.php file.
function add_my_script() {
wp_enqueue_script(
'custom-script', get_template_directory_uri() . '/js/your-script-name.js',
array('jquery')
);
}
add_action( 'wp_enqueue_scripts', 'add_my_script' );
Now you are done.
Registering script in functions has it benefits as it comes in <head> section when page loads thus it is a part of header.php always. So you don't have to repeat your code each time you write a new html content.
#Method 2: put the script code inside the page body under <script> tag. Then you don't have to register it in functions.
You can add custom javascript or jquery using this plugin.
https://wordpress.org/plugins/custom-javascript-editor/
When you use jQuery don't forget use jquery noconflict mode
There are many tutorials and answers here how to add your script to be included in the page. But what I couldn't find is how to structure that code so it will work properly. This is due the $ being not used in this form of JQuery.
So here is my code and you can use that as a template.
jQuery(document).ready(function( $ ){
$("#btnCalculate").click(function () {
var val1 = $(".visits").val();
var val2 = $(".collection").val();
var val3 = $(".percent").val();
var val4 = $(".expired").val();
var val5 = $(".payer").val();
var val6 = $(".deductible").val();
var result = val1 * (val3 / 100) * 10 * 0.25;
var result2 = val1 * val2 * (val4 / 100) * 0.2;
var result3 = val1 * val2 * (val5 / 100) * 0.2;
var result4 = val1 * val2 * (val6 / 100) * 0.1;
var val7 = $(".pverify").val();
var result5 = result + result2 + result3 + result4 - val7;
var result6 = result5 * 12;
$("#result").val("$" + result);
$("#result2").val("$" + result2);
$("#result3").val("$" + result3);
$("#result4").val("$" + result4);
$("#result5").val("$" + result5);
$("#result6").val("$" + result6);
});
});
Answer from here: https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/
Despite the fact WordPress has been around for a while, and the method of adding scripts to themes and plugins has been the same for years, there is still some confusion around how exactly you’re supposed to add scripts. So let’s clear it up.
Since jQuery is still the most commonly used Javascript framework, let’s take a look at how you can add a simple script to your theme or plugin.
jQuery’s Compatibility Mode
Before we start attaching scripts to WordPress, let’s look at jQuery’s compatibility mode. WordPress comes pre-packaged with a copy of jQuery, which you should use with your code. When WordPress’ jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries.
What this boils down to is that you can’t use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use jQuery instead. Take a look at the code below to see what I mean:
function xyz_scripts() {
wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'xyz_scripts');
"We have Google" cit.
For properly use script inside wordpress just add hosted libraries. Like Google
After selected library that you need link it before your custom script: exmpl
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
and after your own script
<script type="text/javascript">
$(document).ready(function () {
$('.text_container').addClass("hidden");
});
</script>
The simplest way to add a script inside your functions.php file (on your theme / child theme) without using wp_enqueue_script is this one:
// CREATE WORDPRESS ACTION ON FOOTER
add_action('wp_footer', 'customJsScript');
function customJsScript() {
echo '
<script>
// YOUR JS SCRIPT
jQuery(function(){
console.log("test");
});
</script>
';
}
As you see, you use the wp_footer action to inject the code.
This may not be a good practice if you use it heavily or if you have to 'speak' with other plugins, etc. But is the fastest way!
You can also put directly the Javascript code inside header.php or footer.php if is a code that will be inserted all-over WordPress
You can use WordPress predefined function to add script file to WordPress plugin.
wp_enqueue_script( 'script', plugins_url('js/demo_script.js', __FILE__), array('jquery'));
Look at the post which helps you to understand that how easily you can implement jQuery and CSS in WordPress plugin.
Beside putting the script in through functions you can "just" include a link ( a link rel tag that is) in the header, the footer, in any template, where ever.
No. You should never just add a link to an external script like this in WordPress. Enqueuing them through the functions.php file ensures that scripts are loaded in the correct order.
Failure to enqueue them may result in your script not working, although it is written correctly.
you can write your script in another file.And enqueue your file like this
suppose your script name is image-ticker.js.
wp_enqueue_script( 'image-ticker-1', plugins_url('/js/image-ticker.js', __FILE__), array('jquery', 'image-ticker'), '1.0.0', true );
in the place of /js/image-ticker.js you should put your js file path.
In WordPress, the correct way to include the scripts in your website is by using the following functions.
wp_register_script( $handle, $src )
wp_enqueue_script( $handle, $src )
These functions are called inside the hook wp_enqueue_script.
For more details and examples, you can check Adding JS files in Wordpress using wp_register_script & wp_enqueue_script
Example:
function webolute_theme_scripts() {
wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
wp_enqueue_script( 'script-name' );
}
add_action( 'wp_enqueue_scripts', 'webolute_theme_scripts' );
I was having some serious issues with all the other answers here, so here's my addition for those who are wanting a more up to date solution.
I know this is not exactly what the OP asked because it uses shortcodes, but this is the only way I could make it work and it has the added benefit of only having the function when the page contains the shortcode.
This doesn't use wp_enqueue_script() nor add_action() functions.
I use the Code Snippets plugin which means that there's no need to fiddle around with functions.php and create new .js files.
In a shortcode, echo the jQuery function as so:
echo '<script type="text/javascript">
jQuery(document).ready(function($) {
//your jQuery code goes here.
});
</script>';
Do you only need to load jquery?
1) Like the other guides say, register your script in your functions.php file like so:
// register scripts
if (!is_admin()) {
// here is an example of loading a custom script in a /scripts/ folder in your theme:
wp_register_script('sandbox.common', get_bloginfo('template_url').'/scripts/common.js', array('jquery'), '1.0', true);
// enqueue these scripts everywhere
wp_enqueue_script('jquery');
wp_enqueue_script('sandbox.common');
}
2) Notice that we don't need to register jQuery because it's already in the core. Make sure wp_footer() is called in your footer.php and wp_head() is called in your header.php (this is where it will output the script tag), and jQuery will load on every page. When you enqueue jQuery with WordPress it will be in "no conflict" mode, so you have to use jQuery instead of $. You can deregister jQuery if you want and re-register your own by doing wp_deregister_script('jquery').
I'm using this plugin with elementor https://wordpress.org/plugins/insert-php/
You can copy and paste your script and call it using a shortcode. Without the need to edit functions.php

Enqueueing jQuery plugin in Wordpress theme template

I made a template called test-stuff.php and tried using jQuery and the jQuery validation plugin in it. I've enqueued the scripts in my functions.php file and the jQuery works fine on other regular pages, but not in my template.
Could someone point out where I went wrong? Do I have to enqueue jquery and the jquery plugin separetely for the template? If I have left out some details, please ask and I will provide. Thanks in advance.
functions.php enqueuing part:
function my_custom_queue() {
wp_enqueue_script('jquery');
wp_enqueue_script( 'validatejq', 'https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js', array( 'jquery' ), '1' );
}
add_action( 'wp_enqueue_scripts', 'my_custom_queue' );
Template file with jquery testing function(I get "no"):
<?php
/* Template name: Test stuff */
?>
<script>
window.onload = function() {
/* test */
if (window.jQuery) {
alert("Yes");
} else {
alert("No");
}
};
</script>
As far as I know, you don't need to enqueue, it is already enqueue by WordPress. Check some of the already included JS libraries. You have not called get_header() and get_footer() either.
You can check out the following link to get the list of already include libraries.
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
You should use get_header() in your page template in order get the header code (including the enqueued scripts) in your page. And you probably want to use get_footer() too. Some scripts are included in the footer.

How to add JS to Wordpress and reference CSS or other scripts?

so I am working on a custom theme in Wordpress. I used to have a whole lot of JS in the head.php, like this:
jQuery(document).ready(function($) {
$('.widgetblock').accordion({
//args
});
if ( have_posts() ) {
//stuff
}
});
However I've since read that the proper way to add JS in Wordpress is to use wp_enqueue_script() in functions.php, so I'm trying to do that. What I've done is just put that same code into a .js file that I've save in the corresponding folder, and I'm then loading it like this:
function script_assets() {
wp_enqueue_script( 'js-code', get_template_directory_uri() . '/js/js-code.js', array( 'jquery', 'jquery-ui-widget' ) );
}
add_action( 'wp_enqueue_scripts', 'script_assets' );
I've added JQuery and JQuery UI as dependencies.
However, that doesn't work. Chrome says that accordion() and have_posts() aren't defined. I also encounter issues if I try to reference specific elements from my CSS.
So, what am I to do? This is probably a very basic problem, but I can't find how to solve it.
Another problem is, how do I make 100% sure that some JS scripts are loaded after the CSS? I'm using -prefix-free which should be loaded right after it, but I'm not sure that's possible with wp_enqueue...
EDIT: I can't really load that script in the footer, it needs to be loaded immediately after the CSS. :/
Thanks.
Every time I have had to add jQuery to a WordPress site I use this code that I found on CSS-tricks
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
wp_enqueue_script('jquery');
}
For what I understand, once you load jQuery this way you prevent conflicts and it gets loaded only once.
Well someone else posted an answer but then deleted it so...
The dependency I was using here wp_enqueue_script( 'js-code', get_template_directory_uri() . '/js/js-code.js', array( 'jquery', 'jquery-ui-widget' ) ); was wrong; I should have used jquery-ui-accordion, which jquery-ui-widget doesn't include. I elected to include the whole of jquery-ui (so I could use other features without having to add specific dependencies for each of them) but to do that I had to link to Google's, since there is no full package in WP.
That fixed some of my issues, not everything (the -prefix-free script still isn't loaded right after the stylesheet, and I have to find a way to replace the PHP functions that I used before) but the website's working, so there's that :)
Thanks to whomever actually answered, I don't remember your username, sorry.

How to implement javascript into Wordpress

I'm having a bit of trouble understanding how to put javascript into a wordpress theme.
I know I have to save this javascript:
http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
and put it in a folder on the server under "js" but what do I do with the functions javascript?
$(document).ready(function(){
$('#contactButton').click(function(){
$('#contactDropDown').show("fast");
$('#contactDropDown').animate({height:'500px'}, 200);
});
$('#closeBox').click(function(){
$('#contactDropDown').hide("fast");
$('#contactDropDown').animate({height:'0px'}, 200);
});
});
Do I save this as a different document but save it to the same "js" folder?
What is the exact code that I need to put into the functions.php of the theme?
i also created a fiddle for a little more understanding: http://jsfiddle.net/ptemyw52/
(the javascript is for the drop down contact box)
You use the WordPress wp_enqueue_script function to tell WordPress what to load.
It has jQuery builtin, so you can just tell it:
wp_enqueue_script('jquery');
to get that. For your own code, put it in a file somewhere (e.g. js/scripts.js) and then tell WordPress to load it with:
wp_enqueue_script(
'myscript',
get_stylesheet_directory_uri() . '/js/scripts.js',
array('jquery')
);
The final argument array('jquery') tells WP that your scripts depend on having jquery.
Wordpress Already has JQuery included.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
You have to make sure is it enqued somewhere. If JQuery is not running either in your functions.php or your head.php enqueue it like so:
wp_enqueue_script('jquery');
Wordpress loads JQuery in no-conflict mode so the bling ($) is not going to work you need to atually type in the jQuery. You can actually just type it out and pass it in through your document ready, like so:
<script>
jQuery(document).ready(function($){
$('#contactButton').click(function(){
$('#contactDropDown').show("fast");
$('#contactDropDown').animate({height:'500px'}, 200);
});
$('#closeBox').click(function(){
$('#contactDropDown').hide("fast");
$('#contactDropDown').animate({height:'0px'}, 200);
});
});
</script>
You can actually just add this to your footer.php if this the only code you have.. If you end up having more javascript you might want to make it's own file and enqueue as well.
in: wp-content/themes/your-template/js you put your js file.
Then in head of document (it could be header, index etc.)
<script src="<?php echo get_template_directory_uri(); ?>/js/your.js"></script>

Wordpress force scripts to load after plugins

I have a custom js file as part of my wordpress installation, which is registered and enqueued using functions.php as normal. I have registered this particular script to load within wp_footer rather than within wp_header. However, I also have a plugin that is putting js into wp_footer, and by default it is loading this below my script. I need to force my script to load last. Is there soemthing simple that can be done to achieve this? It seems like something fairly routine to me?
Here is my code:
function scripts() {
// Register scripts
// js
wp_register_script('custom', get_bloginfo('template_url'). '/js/custom.js', false, false, true);
// Enqueue scripts
wp_enqueue_script('custom');
}
add_action('wp_enqueue_scripts', 'scripts');
The current order of the scripts goes, but I need to force my script to load after the plugin:
<script>/my_script.js</script>
<script>/plugin_script.js</script>
Thanks in advance!
Just set the $priority parameter to a ridiculously high value:
add_action( 'wp_enqueue_scripts', 'scripts', 999999 );
To be the very last in the queue (though one can never be sure) use php's PHP_INT_MAX constant:
add_action( 'wp_enqueue_scripts', 'scripts', PHP_INT_MAX );
Edit cf. discussion in comments. Note that the following is NOT the recommended way of enqueueing scripts in the footer.
add_action( 'wp_print_footer_scripts', 'so26898556_print_footer_scripts', ( PHP_INT_MAX - 2 ) );
function so26898556_print_footer_scripts()
{
echo '<script src="' . get_bloginfo( 'template_url' ) . '/js/custom.js"></script>';
}

Categories