Unlock Posts a Number of Days After Joining
Adds an "Unlock after" field to the post editor so a post's content only appears to members a set number of days after they registered, perfect for e-mail-course style sites.
Opens WPIDE on
Code
// Post types that get the field.
$wpide_drip_post_types = array( 'post', 'page' );
add_action( 'add_meta_boxes', function () use ( $wpide_drip_post_types ) {
add_meta_box( 'wpide-drip', 'Drip schedule', function ( $post ) {
wp_nonce_field( 'wpide_drip', 'wpide_drip_nonce' );
printf(
'<p><label for="wpide-drip-days">Unlock this many days after a member joins</label><br><input type="number" min="0" step="1" id="wpide-drip-days" name="wpide_drip_days" value="%s" style="width:6em"></p>',
esc_attr( get_post_meta( $post->ID, '_wpide_drip_days', true ) )
);
}, $wpide_drip_post_types, 'side' );
} );
add_action( 'save_post', function ( $post_id ) {
if ( ! isset( $_POST['wpide_drip_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['wpide_drip_nonce'] ), 'wpide_drip' ) || ! current_user_can( 'edit_post', $post_id ) || wp_is_post_revision( $post_id ) ) {
return;
}
$days = isset( $_POST['wpide_drip_days'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_drip_days'] ) ) : '';
if ( '' === $days ) {
delete_post_meta( $post_id, '_wpide_drip_days' );
} else {
update_post_meta( $post_id, '_wpide_drip_days', absint( $days ) );
}
} );
add_filter( 'the_content', function ( $content ) {
$post = get_post();
if ( ! $post ) {
return $content;
}
$days = get_post_meta( $post->ID, '_wpide_drip_days', true );
if ( '' === $days || current_user_can( 'edit_post', $post->ID ) ) {
return $content;
}
if ( ! is_user_logged_in() ) {
return '<p class="wpide-drip-locked">This lesson is for members. <a href="' . esc_url( wp_login_url( get_permalink( $post ) ) ) . '">Log in</a> to continue.</p>';
}
$unlocks = strtotime( wp_get_current_user()->user_registered . ' UTC' ) + (int) $days * DAY_IN_SECONDS;
if ( time() >= $unlocks ) {
return $content;
}
return '<p class="wpide-drip-locked">' . esc_html( sprintf( 'This lesson unlocks on %s. See you then!', wp_date( get_option( 'date_format' ), $unlocks ) ) ) . '</p>';
}, 1 );
Notes
Leave the field empty for posts everyone can read. Visitors who are not logged in see a login prompt on dripped posts.
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.