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' );
}
}
Related
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' );
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
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');
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 );
I'm trying to make Cloudflare's Rocket Loader work on my WP site. Everything works fine except for the WP Visual Editor. I followed the advice here but it doesn't work:
How do I add custom attributes to javascript tags in Wordpress?
Cloudflare says that in order to make Rocket Loader ignore a javascript file I need to add the data-cfasync="false" tag before my script:
<script data-cfasync="false" src="/javascript.js"></script>
https://support.cloudflare.com/entries/22063443--How-can-I-have-Rocket-Loader-ignore-my-script-s-in-Automatic-Mode-
Rocket loader doesn't ignore my JS files.
Here's my code:
function rocket_loader_attributes( $url )
{
$ignore = array (
'http://www.mysite.com/wp-includes/js/tinymce/tiny_mce.js?ver=349-21274',
'http://www.mysite.com/wp-admin/js/editor.js?ver=3.4.2'
);
if ( in_array( $url, $ignore ) )
{ // this will be ignored
return "$url' data-cfasync='false";
}
return $url;
}
add_filter( 'clean_url', 'rocket_loader_attributes', 11, 1 );
What is wrong with my code?
I'm currently using Rocket Loader on Automatic mode.
Can anyone help?
Maybe you can point me in the right direction.
Thank you.
I have found the solution for this!
As it's written in this article:
Controlling Cloudflare Rocket Loader
Your script was almost right, but the manual mode is broken. You need to switch to automatic mode, and then make some modifications:
function rocket_loader_attributes_start() {
ob_start();
}
function rocket_loader_attributes_end() {
$script_out = ob_get_clean();
$script_out = str_replace(
"type='text/javascript' src='{rocket-ignore}",
'data-cfasync="false"'." src='",
$script_out);
print $script_out;
}
function rocket_loader_attributes_mark($url) {
// Set up which scripts/strings to ignore
$ignore = array (
'script1.js'
);
//matches only the script file name
preg_match('/(.*)\?/', $url, $_url);
if (isset($_url[1]) && substr($_url[1], -3)=='.js') {
foreach($ignore as $s) {
if (strpos($_url[1], $s)!==false)
return "{rocket-ignore}$url";
}
return "$url' data-cfasync='true";
}
return "$url";
}
if (!is_admin()) {
add_filter( 'clean_url', 'rocket_loader_attributes_mark', 11, 1);
add_action( 'wp_print_scripts', 'rocket_loader_attributes_start');
add_action( 'print_head_scripts', 'rocket_loader_attributes_end');
}
Notice in the example that the tag does not have the type='text/javascript' attribute. For some reason Rocket Loader requires data-cfasync='false' to be used without the type='text/javascript'... a bug?
Your code does add the data-cfasync='false' attribute, but does not override the WordPress behaviour of adding the type='text/javascript' attribute also, which makes Rocket Loader not to "ignore" your script.
It might be tricky to override this WordPress behaviour since the relevant code does not support a filter...
Ernest Marcinko's solution works fine; however a simpler (and potentially safer) solution these days is to use the script_loader_tag hook, added in WordPress 4.1.
See this answer for an example.