Let's say I have this URL: www.mywebsite.com/myCPT/post, here I want to check if 3 days has passed since the post was created to redirect to www.mywebsite.com/myCPT/post/stats.
In this 3 days time frame the user should not be able to access www.mywebsite.com/myCPT/post/stats.
But this needs to be dynamic, everytime a post is created to check for it's URL and add a 3 days time till this URL will be accessible www.mywebsite.com/myCPT/post/stats
For example I will have post1, post2, post3 and so on and everytime the post will be created to add a 3 days time frame till the "/post/stats" will be available.
I've did some research and I found this:
header('Refresh: 10; URL=http://yoursite.com/page.php');
Found also an wordpress function for redirection : wp_redirect( $location, $status );
Another function for getting the date when the post was created :
<?php echo get_the_date(); ?>
and <?php echo get_the_time(); ?>
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"
is built like this:
function wpa121567_rewrite_endpoints(){
add_rewrite_endpoint( 'stats', EP_PERMALINK );
}
add_action( 'init', 'wpa121567_rewrite_endpoints' );
There are also some plugin where you can set custom redirects but no one offers me the functionality to add a time frame.
Any suggestions on how can I achieve this ? Thank you !
RESOLVED BY DOING THIS:
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();
}
}
}
NOTE: THE CODE IS NOT MINE, IS TAKEN FROM HERE