You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击按钮按用户登录状态跳转页面报错:is_user_logged_in未定义

Fixing "Uncaught ReferenceError: is_user_logged_in is not defined"

Hey there! Let's sort out that error you're hitting. The issue here is super straightforward: is_user_logged_in() is a server-side PHP function (most commonly used in WordPress), but you're trying to call it directly in your frontend JavaScript. Browsers can't run or access PHP functions—they only understand client-side code like JS. So we need to pass that login status from the server to your JS first.

Step 1: Pass the login state from PHP to JavaScript

You have two simple ways to do this, depending on your setup:

Option 1: Use wp_localize_script (recommended for WordPress)

This is the cleanest method if you're enqueuing your JS properly in WordPress. Add this to your theme's functions.php file or a custom plugin:

function send_login_status_to_js() {
    // Replace 'your-custom-script' with the handle of your enqueued JS file
    wp_enqueue_script( 'your-custom-script', get_template_directory_uri() . '/path/to/your/script.js', array(), '1.0', true );
    
    // Create a global JS object with the login status
    wp_localize_script( 'your-custom-script', 'SiteSettings', array(
        'isUserLoggedIn' => is_user_logged_in()
    ) );
}
add_action( 'wp_enqueue_scripts', 'send_login_status_to_js' );

Option 2: Embed the status directly in your template

If you're working with a simpler setup or just need a quick fix, add this script tag somewhere in your HTML template (before your custom JS runs):

<script>
    // Create a global JS variable with the login status
    const isUserLoggedIn = <?php echo is_user_logged_in() ? 'true' : 'false'; ?>;
</script>

Step 2: Update your JavaScript code

Now replace the undefined is_user_logged_in() call with the JS variable we just created. Here's how your updated code will look:

// Use SiteSettings.isUserLoggedIn if you went with Option 1, or isUserLoggedIn if you used Option 2
if (SiteSettings.isUserLoggedIn) { 
    localStorage.setItem('mood-board', JSON.stringify(selectedOptions)); 
    window.location.href = "https://manilva.co/click-to-reveal/"; 
} else { 
    localStorage.setItem('mood-board', JSON.stringify(selectedOptions)); 
    window.location.href = "https://manilva.co/register/"; 
}

That's it! Now your JS will have access to the user's login status, and that reference error should disappear.

内容的提问来源于stack exchange,提问作者Manilva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:19:19