Random WordPress Function

Learn about a new WordPress function every day!


Function Signature:

wp_ajax_destroy_sessions

Function Description:

Handles destroying multiple open sessions for a user via AJAX.

Function Examples:

⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Basic usage of wp_ajax_destroy_sessions to clear all user sessions
add_action( 'wp_ajax_destroy_sessions', 'destroy_all_sessions' );

function destroy_all_sessions() {
    session_destroy();
    wp_send_json_success( 'All user sessions have been cleared.' );
}
// Example 2: Using wp_ajax_destroy_sessions to clear specific user sessions based on user ID
add_action( 'wp_ajax_destroy_sessions', 'destroy_specific_user_sessions' );

function destroy_specific_user_sessions() {
    $user_id = $_POST['user_id'];
    $sessions = WP_Session_Tokens::get_instance( $user_id );
    $sessions->destroy_all();
    wp_send_json_success( 'Sessions for user with ID ' . $user_id . ' have been cleared.' );
}
// Example 3: Handling errors and security checks when using wp_ajax_destroy_sessions
add_action( 'wp_ajax_destroy_sessions', 'destroy_sessions_securely' );

function destroy_sessions_securely() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'You do not have permission to perform this action.' );
    }

    $user_id = $_POST['user_id'];
    if ( ! is_numeric( $user_id ) ) {
        wp_send_json_error( 'Invalid user ID provided.' );
    }

    $sessions = WP_Session_Tokens::get_instance( $user_id );
    if ( ! $sessions ) {
        wp_send_json_error( 'No sessions found for user with ID ' . $user_id );
    }

    $sessions->destroy_all();
    wp_send_json_success( 'Sessions for user with ID ' . $user_id . ' have been cleared.' );
}