301 Redirect based on time of day

Hello,

I'd like to set up a 301 redirect that is only active after business hours. It's for a company that would like to have a special page for after-hours support.

It would only work after 5pm on weekdays and be active on weekends.

Does anyone have an idea on how to set this up?

Thanks!

  • Adam
    • Support Gorilla

    Hi Garrett

    I hope you’re well!

    With a small bit of PHP that should be possible. WordPress has a built-in redirect function so we’d just need to add a “time check” to it and a relevant “if” condition. I assume that shouldn’t redirect entire site but just some specific page so basic “flow” would be like (example data):

    if it’s “abc” page and the time of the day is between “7pm and 9am” redirec to “def” page

    <?php

    function wpmu_time_based_page_redirect() {

    // CONFIGURATION - Set your own data here

    $source_page = 7; // ID of the page that should be redirected
    $target_page = 15; // ID of the page user should be redirected to
    $working_hours_start = '9:00'; // start of business hours - 24hr format
    $working_hours_end = '17:00'; // end of business hours - 24hr format

    // END OF CONFIGURATION, DO NOT EDIT BELOW

    $working_hours_start = strtotime( $working_hours_start );
    $working_hours_end = strtotime( $working_hours_end );
    $current_time = strtotime( "now" );

    if ( is_page( $source_page ) && ( ( $current_time < $working_hours_start ) || ( $current_time > $working_hours_end ) ) ) {
    wp_redirect( get_permalink( $target_page ) );
    die;
    }

    }
    add_action( 'template_redirect', 'wpmu_time_based_page_redirect' );

    Note the “configuration” part: you’ll want to adjust values there to your own needs. Please note also that it takes “server time” so if the current time on server differs from the WP time there might need to be some adjustments taken into account.

    To use it on site, simply add it as an “MU plugin”:

    – create an empty file with a .php extension (e.g. “my-time-based-redirect.php”:wink:

    – copy and paste the code into it

    – upload the file to the “/wp-content/mu-plugins” folder of your site’s WP install; if there’s no “mu-plugins” folder in the “wp-content” folder just create an empty one.

    I hope that helps :slight_smile:

    Best regards,

    Adam