Redirect to URL if x number of days passed

Let’s say I have this URL: www.example.com/myCPT/post, here I want to check if 3 days has passed since the post was created to redirect to www.example.com/myCPT/post/stats.

In this 3 days time frame the user should not be able to access www.example.com/myCPT/post/stats.

But this needs to be dynamic, every time a post is created to check for it’s URL and add a 3 days time till this URL will be accessible www.example.com/myCPT/post/stats

For example I will have post1, post2, post3 and so on and every time the post will be created to add a 3 days time frame till the “/post/stats” will be available.

Also I need the same for “/post/comments” : this address should be available after 3 days, and if someone try to access before should be redirected to post url: “/post”

I did some research and I found this:

  • wp_redirect( $location, $status ); for redirection
  • <?php echo get_the_date(); ?> and <?php echo get_the_time(); ?> for gettin the date/time of the post

Found a snippet which might be helpful :

if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
    // DO SOMETHING 
}
return $posts;
}

Later Edit :

The "/stats" and "/comments" endpoints are built like this :

function wpa121567_rewrite_endpoints(){

  add_rewrite_endpoint( 'stats', EP_PERMALINK );

}

add_action( 'init', 'wpa121567_rewrite_endpoints' );

Any suggestions on how can I achieve this?

Solutions Collecting From Web of "Redirect to URL if x number of days passed"

To redirect after 3 days gone after publication, hook into template_redirect, check if is a singular cpt view, check the date and compare to current time and redirect if needed.

In the 3 days time frame, check if stats is is the query vars and if so redirect to post page.

add_action('template_redirect', 'check_the_date_for_stats');

function check_the_date_for_stats() {
  if ( is_singular('myCPT ') ) { // adjust myCPT with your real cpt name
    $pl = get_permalink( get_queried_object() ); // permalink
    $is_stats = array_key_exists( 'stats', $GLOBALS['wp_query']->query ); // is stats?
    $is_cm = array_key_exists( 'comments', $GLOBALS['wp_query']->query ); // is comments?
    $ts = mysql2date('Ymd', get_queried_object()->post_date_gmt ); // post day
    $gone = ($ts + 3) < gmdate('Ymd'); // more than 3 days gone?
    if ( $gone && ( ! $is_stats && ! $is_cm ) ) {
       // more than 3 days gone and not is stats => redirect to stats
       wp_redirect( trailingslashit($pl) . '/stats' );
       exit();
    } elseif( ! $gone && ( $is_stats || $is_cm ) ) {
       // we are in 3 days frame and trying to access to stats => redirect to post
       wp_redirect( $pl );
       exit();
    }
  }
}