How to detect first visit of a user?

I want to build an alert for users who visit my WordPress blog. Is there a conditional function like is_home() to detect if someone visits the blog the first time? I want to send the alert to every new user no matter on which site he entered.

Related posts

Leave a Reply

2 comments

  1. No, there’s nothing in the core like that.

    You can set a cookie and do it simply enough (warning: untested code follows).

    <?php
    function is_first_time()
    {
        if (isset($_COOKIE['_wp_first_time']) || is_user_logged_in()) {
            return false;
        }
    
        $domain = COOKIE_DOMAIN ? COOKIE_DOMAIN : $_SERVER['HTTP_HOST'];
    
        // expires in 30 days.
        setcookie('_wp_first_time', '1', time() + (WEEK_IN_SECONDS * 4), '/', $domain);
    
        return true;
    }
    
    if (is_first_time()) {
         // it's the user's first time, do stuff!
    }
    

    Just make sure you have output buffering turned on or use that before anything gets sent to the screen to make sure the cookie gets set.

  2. Modified a bit from chrisguitarguy. Place in your functions.php file, and use the conditional in theme templates, etc. via the hook

    function is_first_time() {
        if (isset($_COOKIE['_wp_first_time']) || is_user_logged_in()) {
            return false;
        } else {
            // expires in 30 days.
            setcookie('_wp_first_time', 1, time() + (WEEK_IN_SECONDS * 4), COOKIEPATH, COOKIE_DOMAIN, false);
    
            return true;
        }
    }
    add_action( 'init', 'is_first_time');