Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dwanjuki/119ccd568a022485e8559e9d08278b6b to your computer and use it in GitHub Desktop.
Save dwanjuki/119ccd568a022485e8559e9d08278b6b to your computer and use it in GitHub Desktop.
Lock membership content for an additional period. This is handy for memberships that should have access to a members-only post after a certain time has passed depending on their level. E.g. Gold level has immediate access, silver has access after 7 days and bronze after one month the post was published.
<?php
/**
* Set a waiting period before unlocking a members-only post that
* the member's membership level has access to.
*
* To set which posts to unlock and their individual period (days)
* set the post id's as the array key and the period as the
* value of the array key of the $posts_to_unlock variable.
*
* You can add this recipe to your site by creating a custom plugin
* or using the Code Snippets plugin available for free in the WordPress repository.
* Read this companion article for step-by-step directions on either method.
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function period_to_lock_member_only_content_per_membership_level( $hasaccess, $thepost, $theuser, $post_membership_levels ) {
/**
* Set your unlock schedule per level here. (Level ID => time period)
* See https://www.php.net/manual/en/function.strtotime.php
*/
// Level ID => Time to wait
$level_schedule = array(
1 => '1 Month',
2 => '14 Days',
3 => '24 Hours',
4 => '1 Hour',
5 => '30 Minutes',
);
/**
* These levels have access to all restricted posts.
* Suggestion: This could be for your premium level(s)
*
* pmpro_hasMembershipLevel accepts single level id, e.g. pmpro_hasMembershipLevel( 6 ), or
* array of level ids, e.g. pmpro_hasMembershipLevel( array( 6, 7 ) )
*/
// Set your all access level(s) here
if ( pmpro_hasMembershipLevel( array( 6, 7 ) ) ) {
return true;
}
// If user is an admin, allow access.
if ( current_user_can( 'manage_options' ) ) {
return true;
}
// Skip if PMPro says they don't have access.
if ( ! $hasaccess ) {
return $hasaccess;
}
// Should we lock the post?
foreach ( $level_schedule as $level_id => $time ) {
if ( pmpro_hasMembershipLevel( $level_id ) && strtotime( 'now' ) < strtotime( $time, strtotime( $thepost->post_date ) ) ) {
// Set custom content locked message
add_filter( 'pmpro_non_member_text_filter', 'swap_locked_member_text' );
$hasaccess = false;
}
}
return $hasaccess;
}
add_filter( 'pmpro_has_membership_access_filter', 'period_to_lock_member_only_content_per_membership_level', 10, 4 );
function swap_locked_member_text( $s ) {
$s = 'This content is not available yet.';
return $s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment