Search code examples
wordpresscontact-form-7

How to validate current server time in wordpress plugin Contact form 7?


When user clicks on submit button I need to validate current server time and date, and return error message if the server time is not in desired time interval or day (weekend).


Solution

  • Figured it out!

        add_action("wpcf7_before_send_mail", "wpcf7_do_something_else", 15, 3);  
        function wpcf7_do_something_else($cf7, &$abort, $submission) {
            $id = $cf7->id();  // id of your cf7 form
    
            if ($id == 3580) {
    
                $date = date_i18n( get_option( 'date_format' ) );
                $date = explode(" ", $date);
                $day = $date[0];
                $time = date_i18n( get_option( 'time_format' ) );
                $time = explode(':',$time);
                $hour = intval($time[0]);
    
                //custom day and time validation
                if ( ( $day == 'Sunday' || $day == 'Saturday' ) || !( ( 5 <= $hour) && ($hour <= 20) ) || ( $day == "Friday" && $hour >= 20 ) ) {
                    $abort = true; // &$abort reference
                    $submission->set_status( 'validation_failed' );
                    $errMsg = "Your error message"; // custom error message
                    $submission->set_response( $cf7->filter_message($errMsg) ); 
                }
            }
    
            return $wpcf;
        }
    

    Hope this helps someone :)