Trial Accounts That Downgrade After a Set Number of Days
Gives new sign-ups a "trial" role for a limited time (14 days by default) and then switches them to a basic role automatically the next time they visit.
Opens WPIDE on
Code
// Role during the trial, role afterwards, and trial length.
$wpide_trial_role = 'contributor';
$wpide_after_role = 'subscriber';
$wpide_trial_days = 14;
add_action( 'user_register', function ( $user_id ) use ( $wpide_trial_role ) {
if ( current_user_can( 'create_users' ) || ! get_role( $wpide_trial_role ) ) {
return;
}
( new WP_User( $user_id ) )->set_role( $wpide_trial_role );
update_user_meta( $user_id, 'wpide_trial_started', time() );
}, 20 );
add_action( 'init', function () use ( $wpide_trial_role, $wpide_after_role, $wpide_trial_days ) {
$user_id = get_current_user_id();
$started = $user_id ? (int) get_user_meta( $user_id, 'wpide_trial_started', true ) : 0;
if ( ! $started || time() - $started < $wpide_trial_days * DAY_IN_SECONDS ) {
return;
}
$user = wp_get_current_user();
if ( in_array( $wpide_trial_role, (array) $user->roles, true ) ) {
$user->remove_role( $wpide_trial_role );
$user->add_role( $wpide_after_role );
}
delete_user_meta( $user_id, 'wpide_trial_started' );
update_user_meta( $user_id, 'wpide_trial_ended', time() );
} );
add_shortcode( 'wpide_trial_days_left', function () use ( $wpide_trial_days ) {
$started = is_user_logged_in() ? (int) get_user_meta( get_current_user_id(), 'wpide_trial_started', true ) : 0;
if ( ! $started ) {
return '';
}
$left = max( 0, (int) ceil( ( $started + $wpide_trial_days * DAY_IN_SECONDS - time() ) / DAY_IN_SECONDS ) );
return esc_html( sprintf( _n( '%d day left in your trial', '%d days left in your trial', $left ), $left ) );
} );
Notes
Both roles must exist. Accounts made by administrators are not put on trial; [wpide_trial_days_left] shows the days remaining.
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.