duanlun2827 2018-06-13 23:04
浏览 60
已采纳

Wordpress仅在用户未登录时执行javascript文件

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条回答 默认 最新

  • douwei1174 2018-06-13 23:25
    关注

    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' );
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码