0

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!

1

1 Answer 1

1

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' );
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but it doesn't work at all. =/ The ad (popup) is not showing at all. This is the content of the js file: pastebin.com/raw/Zz9CbhJb
The function I gave you is correct, the contents of your JS file aren't correct, however. You can't actually have <script> tags in your .js files. You'll want to break up that script. Save your JS file with the code, starting at K200 alll the way through and omit the last </script> tag. Inside your script though, is another remote script, which you'll have to load in. So once you update your JS file, enqueue the remote file above your personal one: wp_enqueue_script( 'clksite-adserve', '//p28173.clksite.com/adServe/banners?tid=28173_568703_0&tagid=2&hybridPop=true' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.