Expiry Dates for User Accounts
Lets administrators set an expiry date on any account; after that date the user is logged out and can no longer log in, which suits trial or temporary access.
Opens WPIDE on
Code
add_action( 'edit_user_profile', function ( $user ) {
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
return;
}
wp_nonce_field( 'wpide_expiry_' . $user->ID, 'wpide_expiry_nonce' );
printf(
'<h2>Access</h2><table class="form-table" role="presentation"><tr><th scope="row"><label for="wpide-expires">Account expires on</label></th><td><input type="date" id="wpide-expires" name="wpide_expires" value="%s"><p class="description">Leave empty for no expiry.</p></td></tr></table>',
esc_attr( get_user_meta( $user->ID, 'wpide_expires', true ) )
);
} );
add_action( 'edit_user_profile_update', function ( $user_id ) {
if ( ! isset( $_POST['wpide_expiry_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_expiry_nonce'] ), 'wpide_expiry_' . $user_id ) || ! current_user_can( 'edit_user', $user_id ) ) {
return;
}
$date = isset( $_POST['wpide_expires'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_expires'] ) ) : '';
if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) {
update_user_meta( $user_id, 'wpide_expires', $date );
} else {
delete_user_meta( $user_id, 'wpide_expires' );
}
} );
$wpide_is_expired = function ( $user_id ) {
$date = get_user_meta( $user_id, 'wpide_expires', true );
return $date && wp_date( 'Y-m-d' ) > $date;
};
add_filter( 'authenticate', function ( $user ) use ( $wpide_is_expired ) {
if ( $user instanceof WP_User && $wpide_is_expired( $user->ID ) ) {
return new WP_Error( 'wpide_expired', '<strong>Error:</strong> Your access has expired. Please contact us to renew it.' );
}
return $user;
}, 60 );
// Log out people who are already signed in when their date passes.
add_action( 'init', function () use ( $wpide_is_expired ) {
$user_id = get_current_user_id();
if ( $user_id && ! user_can( $user_id, 'manage_options' ) && $wpide_is_expired( $user_id ) ) {
wp_logout();
}
} );
add_filter( 'manage_users_columns', function ( $columns ) {
$columns['wpide_expires'] = 'Expires';
return $columns;
} );
add_filter( 'manage_users_custom_column', function ( $output, $column, $user_id ) use ( $wpide_is_expired ) {
if ( 'wpide_expires' !== $column ) {
return $output;
}
$date = get_user_meta( $user_id, 'wpide_expires', true );
if ( ! $date ) {
return '—';
}
return $wpide_is_expired( $user_id ) ? '<span style="color:#b32d2e">Expired ' . esc_html( $date ) . '</span>' : esc_html( $date );
}, 10, 3 );
Notes
Leave the date empty for accounts that never expire. Dates use the site's time zone.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.