0

I'd like to implement a custom logout function that only runs if the conditions are met. Instead it returns me to the homepage whether the conditions are true or not.
Here's the code that should do the logging out:

function no_cookie() {
    global $noCookiesLeft;
    if($noCookiesLeft) {
         wp_redirect("mysite.com/custom logout");
         exit;
     }
}
add_action('wp_logout','no_cookie',10,2);

And here's the code that should trigger this:

if($cookie_count >= 3) {
    wp_delete_user($id);
    $noCookiesLeft = true;
    wp_logout();   
}

noCookiesLeft is a global variable since I haven't found any other way to do this, and google failed me.

Edit:

function login_cookie($user_login, $user) {
global $wpdb;
global $noCookiesLeft;
$id = $user->ID;

if(!isset($_COOKIE['userCookie'])) {
    if(in_array('administrator', $user->roles))
        $wpdb->delete('wp_cookies',['user_id'=>$id]);

    $cookie_count = $wpdb->get_var("SELECT COUNT(*) FROM wp_cookies WHERE user_id=".$id."");
    if($cookie_count >= 3) {
        wp_delete_user($id);
    }
    else {
        $value = md5($id);;
        setcookie('userCookie', $value, time()+360000*24*100, "", "",false);
        $wpdb->insert("wp_cookies",[
                    'user_id'=>$id,
                    'cookie_value'=>$value
                ],
                [
                    '%d',
                    '%s'
                ]);

        }
     }
 }

add_action('wp_login','login_cookie',10,2);

function no_cookie() {
    wp_redirect("/error);
    exit;
}
 }
  add_action('delete_user','no_cookie',10,2);
  • wp_cookies isn't a Core table. Is this a table you've created? – s_ha_dum May 8 '15 at 22:56
0

You need to be sure that you have noted global $noCookiesLeft; before setting it in the if statement. It may be unset when it runs the no_cookie() function.

  • The variable is initialized to false right before the function. – user2941726 May 8 '15 at 16:19
  • Does the user still get logged out by wp_delete_user if the wp_logout line is removed? Would it make more sense then to use the deleted_user hook? – ambroseya May 8 '15 at 16:25
  • I haven't really thought about that, I'll try it. – user2941726 May 8 '15 at 16:28
  • It worked... sort of. It's redirecting now, but won't log the user out. I can't add wp_logout after wp_redirect, can I? – user2941726 May 8 '15 at 16:54
  • Not in that same location, it will never reach the line. Could you put wp_logout() into the function called by the wp_delete_user hook, followed by the redirect? Sorry, I'm usually more concise with a correct solution but it's not enough of the code to test live. – ambroseya May 8 '15 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.