Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.