如何在WordPress中使用if语句?

时间:2016-02-06 作者:Mike

我看不出如何在下面的过滤器函数中正确使用PHP if语句。如果$_POST 输入有值,但如果任何输入为空,则会出现致命错误。所以我想告诉它不要运行任何代码,因为这些输入中的任何一个都是空的。

add_action( \'gform_after_update_entry_7\', \'add_length_on_update\', 10, 2 );
function add_length_on_update( $form, $entry_id ) {

// get input from form
$date = $_POST["input_3"];
$start = $_POST["input_27"];
$end = $_POST["input_28"];

// convert date and time arrays into datetime formats
$startdate = DateTime::createFromFormat(\'m/d/Y@h:i a\', $date . "@". $start[0].":".$start[1]." ".$start[2]);
$enddate =   DateTime::createFromFormat(\'m/d/Y@h:i a\', $date . "@". $end[0].":".$end[1]." ".$end[2]);

//convert datetimes into seconds to compare
$starttime = strtotime($startdate->format(\'Y-m-d H:i:s\'));
$endtime = strtotime($enddate->format(\'Y-m-d H:i:s\'));

// check to see if the times span overnight
if($starttime > $endtime) {
    $endtime = strtotime($enddate->format(\'Y-m-d H:i:s\') . " +1 day");
}

// perform calculation
$diff = floor(($endtime - $starttime)/30);

GFAPI::update_entry_field( $entry_id, 32, $diff );

}

1 个回复
SO网友:Rituparna sonowal

Here you go..

add_action( \'gform_after_update_entry_7\', \'add_length_on_update\', 10, 2 );
function add_length_on_update( $form, $entry_id ) {
    if( !empty($_POST["input_3"]) && !empty($_POST["input_27"]) && !empty($_POST["input_28"]) ){
        // get input from form
        $date = $_POST["input_3"];
        $start = $_POST["input_27"];
        $end = $_POST["input_28"];

        // convert date and time arrays into datetime formats
        $startdate = DateTime::createFromFormat(\'m/d/Y@h:i a\', $date . "@". $start[0].":".$start[1]." ".$start[2]);
        $enddate =   DateTime::createFromFormat(\'m/d/Y@h:i a\', $date . "@". $end[0].":".$end[1]." ".$end[2]);

        //convert datetimes into seconds to compare
        $starttime = strtotime($startdate->format(\'Y-m-d H:i:s\'));
        $endtime = strtotime($enddate->format(\'Y-m-d H:i:s\'));

        // check to see if the times span overnight
        if($starttime > $endtime) {
            $endtime = strtotime($enddate->format(\'Y-m-d H:i:s\') . " +1 day");
        }

        // perform calculation
        $diff = floor(($endtime - $starttime)/30);

        GFAPI::update_entry_field( $entry_id, 32, $diff );
    }   
}