[Resolved] Post Restriction based on users registration date
This thread is resolved. Here is a description of the problem and solution.
Problem:
Is there a script / function, that you could supply me in which restricts a logged in user from viewing a custom post that is 8 days older than the date of the person's registration?
Is there a script / function, that you could supply me in which restricts a logged in user from viewing a custom post that is 8 days older than the date of the person's registration?
I do understand if this is beyond typical support.
You can use WordPress default hooks for that task, I don't think you'd be necessarily using Toolset features for this specific task.
Please check the example bellow:
function restrict_access_to_old_posts() {
// Check if the user is logged in.
if( is_user_logged_in() ) {
global $post;
// Check if it's a single post page of your custom post type
if( is_singular('your_custom_post_type') ) {
// Get the current user's data.
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$userdata = get_userdata($user_id);
$registered_date = strtotime($userdata->user_registered); // Registration date in Unix timestamp
// Days restriction
$days_restriction = 8;
// Calculate the restriction timestamp
$restriction_timestamp = $registered_date + ($days_restriction * DAY_IN_SECONDS);
// Get the post publication time.
$post_time = get_post_time('U', true, $post->ID); // Post time in Unix timestamp
// Compare the post time with the restriction timestamp.
if( $post_time < $restriction_timestamp ) {
// If post time is older than the user's allowed view range, restrict access.
wp_redirect( home_url() ); // Redirect to homepage or any other page.
exit;
}
}
}
}
add_action( 'template_redirect', 'restrict_access_to_old_posts' );
In the code above you are checking if a user is logged in and on a single post of your custom post type, then it gets the logged-in user's registration date and the post’s publication date. If the post date is older than 8 days from the user's registration date the user is redirected to the home page.
You should replace the custom post type and add this code to your child theme's functions.php file. You may customize it to attend your needs, example you might want to display a message or redirect the user to a different page for example.