i have a website that is running the Master Slider Pro wordpress plugin and the iLightBox plugin. I am running a custom script in a custom.js file in wordpress child theme:
/* Link JavaScript file */
function custom_scripts() {
wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery') , false, true );
wp_enqueue_script( 'custom-script' );
}
I am calling the custom file as per the below in my functions.php file:
jQuery(document).ready(function(){
(function(){
var groupsArr = [];
jQuery('[rel^="ilightbox["]').each(function () {
var group = this.getAttribute("rel");
jQuery.inArray(group, groupsArr) === -1 && groupsArr.push(group);
});
jQuery.each(groupsArr, function (i, groupName) {
jQuery('[rel="' + groupName + '"]').iLightBox({ /* options */ });
});
})();
});
The issue i am having is that sometimes it loads the custom script (i assume in the correct order) and my slider loads and the lightbox displays when i click the image... other times the slider gets stuck in a loading state and shows the errors:
Uncaught TypeError: jQuery(...).iLightBox is not a function
I believe i am loading the custom.js file after the jQuery file has loaded... what i am assuming is, that the lighbox plugin is sometimes loading after the jQuery and therefore loading after custom.js file which is why it cannot find the ilightbox function ?
Anyway i can prevent this ?
I have been doing some reading and spoke to my theme author (who has integrated the ilightbox function).
My code now looks like the below:
/* register script that defines ilightbox (in parent theme) */
wp_register_script( 'ilightbox_script', get_stylesheet_directory . '/includes/class-avada-scripts.php' );
/* Link JavaScript file */
function custom_scripts() {
wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery', 'ilightbox_script') , false, true );
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'custom_scripts', 99 );
I believe i have now registered the script that contains the ilightbox function (stored in my parent theme). I then called the custom.js file after jQuery and the registered script has loaded. However it still is not working. I also get the following error from the file i am now trying to register:
Uncaught SyntaxError: Unexpected token <
Maybe i have misunderstood everything, so i have copied what the theme author has said to me when i asked which fine defines the ilightbox function.. what do you think?
These scripts are enqueued in class-avada-scripts.php available in
following directory
/wp-content/themes/avada/includes
and all JS code is in main.min.js available in following directory
/wp-content/themes/avada/assets/js
However if you enable developer mode from
Wp admin -> appearance -> theme options -> advanced
then you can modify code in avada-lightbox.js and lightbox.js
available in same directory.
UPDATE (22/11/2015):
Latest update has me using:
/* Ensure jquery loads before iLightBox */
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script( 'ilightbox_script', get_theme_root_uri() . '/Avada/includes/class-avada-scripts.php', array( 'jquery' ) );
wp_register_script( 'custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js' );
wp_enqueue_script('ilightbox_script');
wp_enqueue_script('custom-script');
}
Still same error :(
Related
i have this code to import the css it's working fine but not updating my css latest update right now
// style imports
function themeslug_enqueue_style() {
wp_enqueue_style( 'bootstrap', plugins_url('/bootstrap/css/bootstrap.css', __FILE__), false );
wp_enqueue_style( 'my-style', plugins_url('/assets/mystyle.css', __FILE__), false );
}
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );
add_action('showForm', 'showInterface');
this is my plugin directory
turnvoer-calculator
assets
mystyle.css
turnover-calculator.php
If your stylesheet (mystyle.css) success enqueue but it's not update your latest changes - most of the case is because of cache issue (usually have at least 2 layers of cache in a WP site).
So you need to force your WP site to load the newest version of your stylesheet by adding time argument to your stylesheet's url. Your case, using this code:
wp_enqueue_style( 'my-style', plugins_url('/assets/mystyle.css?time=', __FILE__).time(), [], false );
Please replace it with your code and try again.
On one page of my WordPress site i use a photo-gallery. For this i need a js-file. Now the js-file is loading on everypage but its just needed one this specific page with the page id 2. Now the problem is, that is_page(2) is not working in the functions.php because the page id is not set then. Is it still possible to do this via functions.php or would you just add the script in the footer.php?
function footer_scripts()
{
// If query if current Page is not wp-login-php or admin page
if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {
wp_register_script('photo-gallery', get_template_directory_uri() . '/js/back-layer-photo-gallery.js', array('jquery'), '1.3', true);
wp_enqueue_script('photo-gallery');
}
}
add_action('init', 'footer_scripts');
you can add this code in function.php and fill it with the slug name of your page and of your script
// Load conditional scripts
function your_conditional_scripts()
{
if (is_page('pagenamehere')) {
wp_register_script('scriptname', get_template_directory_uri() .
'/js/scriptname.js', array('jquery'), '1.0.0'); // Conditional
script(s)
wp_enqueue_script('scriptname'); // Enqueue it!
}
}
add_action('wp_print_scripts', 'your_conditional_scripts'); // Add
Conditional Page Scripts
You can use page slug instead of page ID and use 'wp_enqueue_scripts' instead of 'init'. If you are using child theme use 'get_stylesheet_directory_uri()' in place of 'get_template_directory_uri()' otherwise you can leave it as it is.
add_action('wp_enqueue_scripts', 'enqueue_script');
function enqueue_script() {
if (is_page('page_slug_here')) { // Add slug in condition
wp_enqueue_script('photo-gallery', get_template_directory_uri().'/js/back-layer-photo-gallery.js', array( 'jquery' ), '1.0', true);
}
}
I have a simple script that appends a class on scroll depth and would like to use it on my Wordpress site.
How should I go about adding it? I have the class pinpointed and know the CSS side, but I don't know how to get the script to register.
The script is:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$(".header").addClass("active");
} else {
$(".header").removeClass("active");
}
});
In your (child) theme's functions.php, add the following lines at the end:
function my_enqueue_script()
{
wp_enqueue_script( 'my_custom_script', get_template_directory_uri() .
'/js/my_custom_script.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_script' );
with your script inside the theme's subfolder '/js/my_custom_script.js'. Rename my_custom_script.js to anything you like.
I enqueue a bunch of scripts into the footer of my page:
function core_scripts() {
wp_deregister_script('jquery');
wp_register_script('jquery', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js', false, null, true);
wp_register_script('bootstrap', '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js', array('jquery'), '3.1.1', true);
wp_register_script('flexslider', get_template_directory_uri().'/js/jquery.flexslider-min.js', array('jquery'), '2.2.2', true);
wp_register_script('jqzoom', get_template_directory_uri().'/js/jquery.jqzoom-core-pack.js', array('jquery'), '2.3', true);
wp_register_script('fancybox', get_template_directory_uri().'/js/jquery.fancybox.pack.js', array('jquery'), '2.1.5', true);
... a bunch of others ...
}
add_action('init', 'core_scripts'); // Add Custom Scripts
function write_site_scripts()
{
wp_enqueue_script('jquery');
wp_enqueue_script('bootstrap');
wp_enqueue_script('flexslider');
wp_enqueue_script('jqzoom');
wp_enqueue_script('fancybox');
...etc...
}
add_action('wp_enqueue_scripts', 'write_site_scripts'); // write all enqueued scripts
function write_custom_scripts()
{
$html = "<!-- Custom script -->
<script>
var custom = '1';
</script>";
echo $html;
}
add_action('wp_footer', 'write_custom_scripts'); // this script writes in the footer before the dependent js scripts
My problem is that the custom script is always written to the page before the jQuery scripts, I guess because the custom script is written to the page via an echo write command.
How can I add custom javascript code into the footer after the jQuery scripts have been written to the page? ie. I need to delay the add_action('wp_footer', 'write_custom_scripts'); to be executed at a later moment, or how can I use enqueue to add a custom javascript?
Note I have removed the CDN code posted earlier since this leads everyone into another discussion - a valid one, but it's not the issue I am after at this moment.
Edit II
Since the question has changed in essence many times, and In order to save you from reading ( e.g. - understanding ) all of the long explanation below, just use .
add_action('wp_footer', 'write_custom_scripts',9999);
This will set the priority to very high and will probably echo your code last ( unless you or other plugin / theme developers used a higher priority or later filter ..)
For those who want to do the right way :
function my_javascripts() {
wp_enqueue_script('the-script-handle',
'path/to/file.js',
array('jquery','other_script_that_we_depend_on'),
'scriptversion eg. 1.0',
true);
}
add_action('wp_enqueue_scripts', 'my_javascripts');
When you enqueue a script like above ( the right way ) , you can see that it wp_enqueue_script() has 4 arguments.path, dependencies ,version ,and in-footer .
This is the only right way to load a script , and if you need , just enqueue also jquery at the same function -- wp will make sure it loads first .
The dependencies means that wp will not load your script UNLESS jQuery is already loaded and will try to load jQuery FIRST ...
The LAST argument will actually define weather to load your script in the FOOTER ( TRUE ) or in header ( FALSE )
That being said , you can always load jQuery in the HEADER and not footer ( but it is not so recommended )
After that , For the last bit of your script , you can echo it in the footer , and you can also control how and when to add it .
What I do not understand , is the overall aim of your method . ( this part is about the "doing it wrong " )
Firstly - I think that loading from CDN is not a good IDEA . AND I AM NOT ALONE. it is to be considered a bad practice in WP without any meaningful Pros ( the time issue is a joke since you will be probably loading a LOT of other scripts directly AND scripts are Cached ).
While doing it - it is good that you think of a fallback, but the fallback should be wp own version - and not one that you include yourself .
If you still insist on doing it wrong , you can always do something like ( or just change order of execution ):
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_footer_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
// your stuff
add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_footer_scripts', 5);
Which basically allow you to echo your stuff before or after the wp_footer action at will And while technically it will work -. it is still wrong .
Edit I After question edit .
you have several problems in that code .
you are registering jQuery (CDN ) with the handle jquery which is reserved for WP.
If you want to do that ( and you shouldn´t . please don´t ) you need to deregister jquery BEFORE registering it again .
<?php wp_deregister_script( 'jquery' ); ?>
Again. I can not stress enough how wrong that is .
2 . you are registring the whole bunch of script - but where do you enqueue them ?
3 . Again . Like in comments ( I think you still do not understand )
If you have a script to add to the footer - you need to register and enqueue it with dependencies .. ( the right way )
In your case from edited question :
make a file called my_script.js
var custom = '1';
Enqueue it !
wp_enqueue_script('the-script-handle',
'path/to/my_script.js',
array('jquery','other_script_that_we_depend_on'),
'0.0.1',
true);
In this case , your script will load AFTER the dependencies you listed ...
What you are trying to do is echoing directly .
As for the comment of how to correctly pass variables - read here
And you can also do something like this ( objects ):
$data = (object) array(
'render' => 'canvas',
'size' => 100,
'radius' => ($q_corner_r * 0.3),
);
$output .=
<script type="text/javascript">;
//<![CDATA[
var options = ' . json_encode($data) . '
// ]]>;
</script>';
When custom php function is called, need to register and enqueue script from within that called function. Then the whole thing gets added to wp_footer hook.
the echoed div in code below shows up in the developer tool, but the script is not showing or even giving any errors, i.e.- if this were an issue with the file path, then there would be resource error, yes? Any comments as to why there wouldn't be an error in loading the script?
The code:
if(get_option('show_content')) {
function add_time() {
echo '<div id="txt">' . '</div>';
// add script tut pro word plugin dev ch12.3
function py_enqueue_script () {
wp_register_script( 'timescript', plugin_url('../time.js', __FILE__));
wp_enqueue_script( 'timescript');
} // end py_enqueue_script
add_action('wp_enqueue_scripts', py_enqueue_script);
} // end show add_time
add_action("wp_footer",add_time);
} // end if
Try this (spotted some syntax errors):
if(get_option('show_content')) {
function add_time() {
echo '<div id="txt">' . '</div>';
// add script tut pro word plugin dev ch12.3
function py_enqueue_script () {
wp_register_script( 'timescript', plugins_url('../time.js', __FILE__), false, null, false));
wp_enqueue_script( 'timescript');
} // end py_enqueue_script
add_action('wp_enqueue_scripts', 'py_enqueue_script');
} // end show add_time
add_action('wp_footer', 'add_time');
} // end if
Brackets on add_action custom action (i.E. 'add_time' instead of add_time).
Plugins URL Function goes plugins_url not plugin_url
Some very good additional article on enqueueing scripts: http://wp.tutsplus.com/tutorials/the-ins-and-outs-of-the-enqueue-script-for-wordpress-themes-and-plugins/
Some additional info on plugins_url:
http://codex.wordpress.org/Function_Reference/plugins_url