简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM