You can log out the current user with wp_logout()
function:
I think it is much better approach. wp_logout()
destroys current session, clears authorization cookie and call wp_logout
action. Also, it is a pluggable function, which means can be redefined by plugins. You can miss important stuff, specially when working in combination with other plugins.
If you want to log out from JavaScript, you can execute wp_logout()
using ajax (code not tested, just writted here as basic example):
add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts()
wp_enqueue_script( 'cyb-ajax-logout', 'url_to_js_script', array( 'jquery' ) );
wp_localize_script( 'cyb-ajax-logout', 'ajax_logout_params',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'logout_nonce' => wp_create_nonce( 'cyb-logout-nonce' ),
)
);
}
add_action('wp_ajax_cyb_logout', 'cyb_ajax_logout');
function cyb_ajax_logout(){
if( check_ajax_referer( 'cyb-logout-nonce', 'logout_nonce', false ) ) {
wp_logout();
$reponse = array(
'message' => __( 'You have been logged out.', 'cyb-textdomain' )
);
wp_send_json_success( $reponse );
} else {
// Ajax referer is wrong
$reponse = array(
'message' => __( "Unknown referer. You couldn't been logged out.", 'cyb-textdomain' )
);
wp_send_json_error( $reponse );
}
}
And the js:
jQuery(document).ready(function($){
var data = {
action: 'cyb_logout',
logout_nonce: ajax_logout_params.logout_nonce
};
$.getJSON( ajax_logout_params.ajax_url, data, function( response ) {
if( response.success ) {
// User has been logged out
}
});
});