wordpress how to add javascript to wp-admin - javascript

I am having a hard time on an easy task but seems like I can not find the answer.
I need to add some js code to the wp-admin page of a wordpress and woocommerce.
For this I have the following code on the functions.php:
function my_enqueue() {
wp_enqueue_script('chcol01', plugin_dir_url(__FILE__) . '/aldisjs/admChangeColorScr.js');
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
and I have this code on admChangeColorScr.js located on plugins/aldisjs:
function chcol(){
alert("now what?");
}
What I expected is an alert notice on the wp-admin page when I relod but it does not happen.
What I am doing wrong??

First of all, you've defined the chcol function in your javascript file BUT YOU HAVE NEVER CALLED/USED IT!
Second point in your code, when you try to inject your js file to admin (or any other page on wordpress), first check whether you're actually on that page or not. Although, admin_enqueue_scripts action hook should do the trick for you.
For example, in your case, first check whether you're actually on the admin panel or not then inject/enqueue your js file! It never hurts to double check!!!
function my_enqueue() {
if(is_admin()){ // if it returns true
// Then run wp_enqueue_script() function!
}
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );

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

Javascript Moodle

Hi I am fairly new to moodle. I have been trying to test if my Javascript runs but to no avail. Here is what I have:
In /videojs/amd/src I made a test.js file with a simple command
define(['jquery'], function() {
return {
init: function() {
// Put whatever you like here. $ is available
// to you as normal.
alert("It changed!!");
}
};
});
Then I grunt the file and everything succeed, and made minified. But when I go to the page it doesn't run. Now I read Moodle's Javascript Doc and I see it says
The idea here is that we will run the 'init' function from our (PHP) code to set things up. This is called from PHP like this...
Where do I call this PHP?
Somewhere in the page you are outputting, you need to add a call like this:
$PAGE->requires->js_call_amd('PLUGINTYPE_videojs/test', 'init);
It's not entirely clear from your example what sort of plugin you are creating, so whichever type you are creating (https://docs.moodle.org/dev/Plugin_types), you need to put it in the appropriate subdirectory for your site (e.g. /mod/videojs, /local/videojs, etc.), then add some sort of PHP script as the entry point for your plugin and call the js_call_amd function from there.

TypeError Jquery(...).function is not a function

I'm having an issue with calling a method that has got me completely stumped. I have a set of methods in an external js class that's used for libraries outside core js for the WP theme.
(Sorry About the unending line)
external.js
(function(a){
var b=0;a.fn.mobileMenu=function(c){function e(a){return a.is("ul, ol")}function f(){return a(window).width()<d.switchWidth}function g(c){if(c.attr("id")){return a("#mobileMenu_"+c.attr("id")).length>0}else{b++;c.attr("id","mm"+b);return a("#mobileMenu_mm"+b).length>0}}function h(a){if(a.val()!==null){document.location.href=a.val()}}function j(b){b.css("display","none");a("#mobileMenu_"+b.attr("id")).show()}function k(b){b.css("display","");a("#mobileMenu_"+b.attr("id")).hide()}function l(b){if(e(b)){var c='<div class="td_mobile_menu_wrap"><select id="mobileMenu_'+b.attr("id")+'" class="mobileMenu">';c+='<option value="">'+d.topOptionText+"</option>";b.find("li").each(function(){var b="";var e=a(this).parents("ul, ol").length;for(i=1;i<e;i++){b+=d.indentString}var f=a(this).find("a:first-child").attr("href");var g=b+a(this).clone().children("ul, ol").remove().end().text();c+='<option value="'+f+'">'+g+"</option>"});c+="</select></div>";b.parent().append(c);a("#mobileMenu_"+b.attr("id")).change(function(){h(a(this))});j(b)}else{alert("mobileMenu will only work with UL or OL elements!")}}function m(a){if(f()&&!g(a)){l(a)}else if(f()&&g(a)){j(a)}else if(!f()&&g(a)){k(a)}}var d={switchWidth:td_switch_width_normal,topOptionText:"Menu",indentString:"-"};return this.each(function(){if(c){a.extend(d,c)}var b=a(this);a(window).resize(function(){m(b)});m(b)})}})(jQuery);
And then the core
site.js
jQuery('#td-top-menu .sf-menu').mobileMenu();
and i end up with the error:
Uncaught TypeError: jQuery(...).mobileMenu is not a function
Somewhere along the line, i've managed to break this code and yet i'm not truly sure. I've stripped my header down to just the necessary scripts and nothing causes the error. My current JQuery CDN is the standard downloaded one from google cdn. I was under the impressional that i would get this issue because it cannot resolve the method. But if both scripts are there (I've logged external.js method to see that the script isn't broken), i don't see why it's throwing this error.
The site is http://whatzbuzzing.com to see the error first hand. As a wordpress distribution, i was under the impression that something has gone wrong outside the two files shown because they haven't been edited at all.
In accordance with the order of requests in Chrome Networks panel, you're loading external.js before jquery.min.js. Maybe you could try to fetch jquery.min.js before fetching of external.js? Sorry if I missed anything in your question.
this happens when multiple jquery files are loaded, not a very uncommon thing in a wordpress site.
in your case the problem is here
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
jquery comes bundled with wordpress, all you have to do is to properly enqueue your script with jquery as a dependency
function enqueue_my_external_script() {
wp_enqueue_script( 'externaljs', '//example.com/path/to/external.js', array( 'jquery') );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_external_script' );
if you're calling this from a theme you can use get_template_directory_uri to get the theme directory's url like this
function enqueue_my_external_script() {
wp_enqueue_script( 'externaljs', get_template_directory_uri() . '/path/to/external.js', array( 'jquery') );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_external_script' );
wp_enqueue_script function
wp_enqueue_scripts action hook

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.

Adding a variable into a page - wordpress

When I create pages within Wordpress, the call to action links on those pages always have the same URL. I want to be able to globalize this variable but am struggling to find a good way to do it.
If I were making simple PHP pages I could simply include e.g.
$URLpath = "http://example.com/my/page";
Then call this in the html:
Call to action
Obviously I can't do this within the Wordpress CMS as it renders as <?=$URLpath?>
I could add, say, Call to action and replace after the page loads using javascript replace over the whole block of html, but it doesn't feel efficient to do this.
Is there a better way? I'm pretty new to Wordpress.
You can add a shortcode in your functions.php file that prints your cta, or better create a plugin with some parameter that manages this link.
For example in functions.php you could add
function cta_func( $atts ){
$URLpath = "http://example.com/my/page";
return 'Call to action';
}
add_shortcode( 'cta', 'cta_func' );
inside your pages/post you can write simply this shortcode.
...
[cta]
...
Further infos about shortcodes are in the reference of codex
https://codex.wordpress.org/Shortcode_API
A good way to do this within WordPress is to use their wp_localize_script()
In your functions.php file you could use as:
// For sake of example I will put your data inside an array,
// but you can set a single value.
$dataForJS = array(
$URLPath => "http://example.com/my/page"
);
// wp_localize_script() takes 3 parameters:
// 1. Name of the registered script, this is the name you used in wp_register_script()
// here I am naming it "main" but it can be anything.
// 2. Name of the variable.
// This name is then available in your JS and will contain your data.
// 3. The data you want to pass, it can be a single value or array
wp_localize_script( 'main', 'd', $dataForJS );
In your JavaScript, you will be able to access this data by just calling the variable d.
What this does is that if the page requests the "main" script, WordPress will add a script tag with your data inside it and makes sure it is placed before your "main" script runs.

Categories

Resources