wp_localize_script with handle jquery - wordpress script - javascript

I'm looking for next solution. I want faster website so I concat all JS to one file and placed in footer. One of my js is jQuery and I use next hook and function:
if (!function_exists("ef_theme_scripts")) {
function ef_theme_scripts() {
wp_deregister_script('jquery');
wp_register_script('jquery', get_template_directory_uri() . '/js/min/script.min.js', null, null, true);
wp_enqueue_script('jquery');
$params = array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('user_nonce'),
);
wp_localize_script( 'jquery', 'ajax_object', $params );
}
}
add_action('wp_enqueue_scripts', 'ef_theme_scripts');
I called my handle "jquery" because there can be some scripts (e.g. from plugins) which wants use jquery so I need add called this handle "jquery".
Everything works great except localize. When I rename script handle for example to "custom-jquery" then wp_localize_script works without problem.
I use WP 4.0.1. Thanks for help

IMPORTANT! wp_localize_script() MUST be called after the script it's being attached to has been registered using wp_register_script() or wp_enqueue_script().
More info

I asked a similar question and got the working solution here :
wp_localize_script not working with jquery handle
Basically this has to do with the way that WP works with the jQuery handle, you'll need to
deregister jquery
deregister jquery-core
Use the jquery-core handle on your script
at the end register jquery, with a dependency on jquery-core and passing false for the $scr attribute
Code:
wp_register_script( 'jquery', false, array( 'jquery-core' ), false, true );

Related

Wordpress execute javascript file only if user is not logged in

I'm trying to execute a javascript file in wordpress only if the user is not logged in, but I can't see why it's not working. This is the code I'm using:
<?php
if ( is_user_logged_in() ) {
echo 'Ok!';
} else {
wp_enqueue_script(
'ads'
);
}
?>
And this is what I have in functions.php to register the file:
wp_register_script(
'ads',
get_bloginfo('template_directory') . '/js/ads.js'
);
Any ideas? Thanks in advance!
wp_enqueue_script() should be run on the wp_enqueue_scripts hook. This should also be encapsulated in a function, or at least a closure/anonymous function.
Side note, you'll want to start properly formatting/indenting code now - future you thanks you!
A. You're checking if a user "is" logged in. You can just make sure that is_user_logged_in() is returning false with the use of the "Not" Logical Operator: !.
B. You don't need to register your script, as wp_enqueue_script will register it for you. You really only need to register scripts if you're getting more fancy like loading scripts only if a shortcode is active on a page.
C. Typically you'll want to prefix your script/style handles, since they should be unique, there can be conflicts otherwise.
D. Typically you'll want to use get_template_directory_uri() or get_stylesheet_directory_uri() over get_bloginfo() since get_bloginfo( $directory_type ) is literally just a wrapper for those functions.
Something like this will get you started:
add_action( 'wp_enqueue_scripts', 'load_ads_script' );
function load_ads_script(){
if( !is_user_logged_in() ){
// The "!" makes sure the user is _not_ logged in.
wp_enqueue_script( 'jacob-k-ads', get_stylesheet_directory_uri().'/js/ads.js' );
}
}

Wordpress plugin doesn't work

Spin360 doesn't work:
All scripts are connected into functions.php
add_action('wp_footer', 'add_scripts');
function add_scripts() {
if(is_admin()) return false;
wp_deregister_script('jquery');
wp_enqueue_script('remodal', 'http://code.jquery.com/jquery-3.0.0.min.js','', '',true);
wp_enqueue_script('remodal', get_template_directory_uri().'/js/jquery.threesixty.js','','',true);
wp_enqueue_script('remodal', get_template_directory_uri().'/js/spinspin.js','','',true);
}
Jquery.threesixty.js -> http://www.mathieusavard.info/threesixty/demo.html
Spinspin.js:
jQuery(function($){
$("#spin").threesixty({images:["...", "..."], method:'click', direction:'forward', sensibility: 1});
});
Article page:
<div id="spin"></div>
<script> if (window.jQuery) {
alert('Connected'); //Return Connected
}
</script>
Page -> http://okwood.by/2016/05/iv78-optima/
Since wordpress uses jQuery.noConflict() to prevent collisions with any other library that might use $ alias you either need to replace $ in your code with jQuery or insulate your code in an IIFE like:
;(function($){
// make sure document is ready
$(function(){
$("#spin").threesixty({images
});
})(jQuery);
OR
jQuery(function($){
$("#spin").threesixty({images
});
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.
You can't use $ in jQuery script, try instead jQuery (replace $ with jQuery).
Wrap your code like this
jQuery(document).ready(function( $ ) {
//Code Here
});
Wordpress ships with jQuery in noConflict mode but when you load jQuery from CDN I don't think that the case. Another point is that the first param for wp_enqueue_script() function is string $handle, each handle should be unique. It is also highly recommended to define script dependencies to ensure loading of all the dependencies it needs. Try this example:
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://code.jquery.com/jquery-3.0.0.min.js', [], false, true );
wp_register_script( 'threesixty', get_template_directory_uri().'/js/jquery.threesixty.js',[ 'jquery' ], false, true );
wp_enqueue_script( 'remodal', get_template_directory_uri().'/js/spinspin.js', [ 'threesixty' ], false, true );
And very important, wp_enqueue_scripts is the proper hook to use when enqueuing items, not wp_footer.

TypeError: $ is not a function

I'm trying to use PinchZoomer, a Jquery plugin on a Wordpress Website but I get this error twice in firebug: TypeError: $ is not a function
I know I should use "jQuery" instead of the $ sign in Wordpress but it doesn't make a difference in this case. Here's my code:
<script type="text/javascript">
jQuery( document ).ready(function($) {
$(".pinchzoom").pinchzoomer();
});
</script>
And here's my code to enqueue jQuery and the PinchZoomer plugin in Wordpress:
function add_jQuery_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('hammer', get_template_directory_uri() . '/pinchzoomer/jquery.hammer.min.js', array() );
wp_enqueue_script('mousewheel', get_template_directory_uri() . '/pinchzoomer/jquery.mousewheel.min.js', array() );
wp_enqueue_script('pinchzoomer', get_template_directory_uri() . '/pinchzoomer/jquery.pinchzoomer.min.js', array() );
wp_enqueue_script('modernizr', get_template_directory_uri() . '/pinchzoomer/modernizr.min.js', array() );
wp_enqueue_script('tweenmax', get_template_directory_uri() . '/pinchzoomer/TweenMax.min.js', array() );
}
add_action('wp_enqueue_scripts', 'add_jQuery_scripts');
This is the page where pinchzoomer should work.
What am I missing?
The initial problem
According to the Wordpress docs for wp_enqueue_script, in the third parameter are the dependencies for that file.
This parameter is optional and accepts a type of array. So that jQuery can be used for that file all you would need to do is add it to as a dependency.
For example:
wp_enqueue_script( 'tweenmax', get_template_directory_uri() . '/pinchzoomer/TweenMax.min.js', array('jquery'));
You can read more about this here where the docs explain about 'Linking a Theme Script Which Depends on jQuery'.
Possibly redundant code
I don't think you need to have this part in your code as I think that Wordpress comes with jQuery and you would be defining it as a dependency while 'enqueue-ing' the relevant scripts :
wp_enqueue_script('jquery');
No Conflict Mode
Finally, for the comment about putting jQuery in no conflict and having the dollar symbol present in the function.
By having the dollar symbol in the brackets next to function, this is basically just introducing the $ symbol to the local scope as a way of accessing jQuery without having to re-type jQuery every time while in 'no conflict' mode.
i.e. It's just a shorter way of accessing it. You can read about no conflict wrappers in Wordpress and about using $ for short here in the docs.
Therefore using the library in the following way should be fine.
jQuery(document).ready(function($) {
$(".pinchzoom").pinchzoomer();
});
Problems with PinchZoomer
From looking at the plugins source code and as we discussed in the comments, it could possibly be a problem with the PinchZoomer plugin itself on line 1440 as they have not themselves made $ available to their local scope.
You can test this by setting a breakpoint online 1440, refreshing the page and setting the value of $ to jQuery. If you have access to the source code your self you could make the fix, although really they should make the fix themselves.
The broken code on lines 1433 - 1442 should be fixed to look like the following code:
(function($)
{
function onReady()
{
PinchZoomer.init();
}
$(onReady);
}(jQuery));
When I go to the page you referenced if I evaluate $ in the console I get undefined, but jQuery is defined. I think your issue may be the callback variable, if jQuery is defined than you shouldn't have to worry about $ being defined unless there is a library conflict.
This should work:
jQuery( document ).ready(function() {
$(".pinchzoom").pinchzoomer();
});
Here is a short-hand version of what you are doing:
jQuery(function() {
$(".pinchzoom").pinchzoomer();
});
// Or
$(function() {
$(".pinchzoom").pinchzoomer();
});
As an Anonymous Function
Another alternative would be to wrap your jquery within an anonymous function:
(function($) {
// All of your jquery calls inside of here
$(function() {
$(".pinchzoom").pinchzoomer();
});
})(jQuery);
You can add this code before ready function.
$=jQuery;
Also please use $ or jQuery in second line you use $ please use jQuery and check.

Wordpress wp_register_script() error

I am getting following error in my wordpress plugin while registering a js file.
PHP Notice: wp_register_script was called incorrectly.
Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks.
Please see Debugging in WordPress for more information.
(This message was added in version 3.3.) in /home/wholesale/public_html/wp-includes/functions.php on line 3547
Please also
add_action('wp_enqueue_scripts', 'enq_shipping_js', 1000);
function enq_shipping_js(){
wp_register_script('customCheckout', WP_PLUGIN_URL . '/woocom_shippingByWeight/js/customCheckout.js', array('jquery'), '2.0.0', true);
wp_enqueue_script('customCheckout');
}
Please help in resolving as calling the wp_register_script() function inside the wp_enqueue_scripts action hook also not resolving it.
Try to use this hook
add_action('admin_init', 'enq_shipping_js');
or use this functions to your functions.php
function enq_shipping_js() {
wp_register_script (
'customCheckout',
WP_PLUGIN_URL . '/woocom_shippingByWeight/js/customCheckout.js',
array('jquery'),
2.0.0,
true
);
}
add_action('wp_enqueue_scripts', 'enq_shipping_js');
enqueue script function
function register_all_styles()
{
wp_enqueue_script( 'customCheckout' );
}
add_action('wp_enqueue_scripts','register_all_styles');

Wordpress Custom Theme: mixing php and javaScript?

I am building a custom wordpress theme and I am trying to add some JavaScript functions.
The main function I want to add is a div that changes color over time. The colors it changes to are defined by the theme color settings in the Customize register. I have added those color settings boxes as show below through my functions.php:
$wp_customize->add_setting('color1', array('default' => '#000000', 'transport'=>'refresh',));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'color1_CNTL', array(
'label' => __('Color 1', 'myTheme'),
'section' => 'colors',
'settings' => 'color1',)));
all of that works fine and I can use it in the Customize register on my admin page. Now, the only thing I'm wondering is, how do I use the value of color 1 in my javaScript code? I know that if I wanted to use it in css I would just have to use
<?php echo get_theme_mod('color1'); ?>
but that doesn't work in JavaScript. Any ideas?
The "WordPress way" would be to localize the script.
Utilize wp_localize_script
Overview:
Register a script in your theme (usually in your functions.php
file). See here:
wp_enqueue_script
Localize the script
Then, access that value via your javascript.
Minimal complete example (compiled from WP docs):
PHP:
add_action('wp_enqueue_scripts', 'my_theme_scripts');
function my_theme_scripts() {
// Register the script first.
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Now we can localize the script with our data.
$color_array = array( 'color1' => get_theme_mod('color1'), 'color2' => '#000099' );
wp_localize_script( 'some_handle', 'object_name', $color_array );
// The script can be enqueued now or later.
wp_enqueue_script( 'some_handle' );
}
Javascript (in your 'myscript.js' file);
// Access the color via the object name defined in localize_script
var color = object_name.color1;
prob
var myvariable='<?php echo get_theme_mod("color1");?>'; //note the surrounding ''!
if you are having issues accessing the variable, declare it a global.

Categories

Resources