[英]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. 仅当用户未登录时,我才尝试在wordpress中执行javascript文件,但是我看不到为什么它不起作用。 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: 这就是我在functions.php中注册文件的内容:
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. wp_enqueue_script()
应该在wp_enqueue_scripts
钩子上运行。 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: !
is_user_logged_in()
:您正在检查用户是否“登录”。您可以使用“非”逻辑运算符确保is_user_logged_in()
返回false !
. 。
B. You don't need to register your script, as wp_enqueue_script
will register it for you. B.您不需要注册脚本,因为
wp_enqueue_script
会为您注册。 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. C.通常,您需要为脚本/样式句柄加上前缀,因为它们应该是唯一的 ,否则可能会发生冲突。
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 . D.通常,你会希望使用
get_template_directory_uri()
或get_stylesheet_directory_uri()
在get_bloginfo()
因为get_bloginfo( $directory_type )
是真的只是为这些功能的包装 。
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' );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.