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 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败