两个if语句,它们分别工作但不能一起工作,PHP

时间:2014-12-19 22:08:58

标签: php wordpress woocommerce conditional-statements custom-fields

我在WordPress工作,在Woo commerce的扩展中。我在结帐页面上有两个自定义字段,当用户输入值存在于数据库中时,它们既是保存也是报告通知,而另一个则不存在。这两个字段都可以自行工作,但当两个字段都处于活动状态时,无论输入哪个字段,第一个条件都会抛出错误。

我正在使用的代码

// process the checkout
function jm_custom_checkout_field_process() {

        // Access the database 
        global $wpdb; 

        // query the database
        $meta_key = '_create_new_group';
        $groupnames = $wpdb->get_col($wpdb->prepare("
            SELECT meta_value 
            FROM $wpdb->postmeta 
            WHERE meta_key = %s" 
            ,$meta_key
        ));

        // get value from user
        $newgroupname = $_POST['create_new_group'];

        // get value from user
        $existing_groupname = $_POST['add_to_existing_group'];

        // check if user input is in array
        if( in_array($newgroupname, $groupnames ) ) {
           wc_add_notice( __( 'Group name already taken.' ), 'error' );
        }
        // check if user input is in array 
        if( ! in_array($existing_groupname, $groupnames ) ) {
            wc_add_notice( __( 'Group name does not exist.' ), 'error' );
        }
}
add_action('woocommerce_checkout_process', 'jm_custom_checkout_field_process');


// save the extra field when checkout is processed
function jm_save_extra_checkout_fields( $order_id, $posted ){

    // Check if there is user input and save
    if( isset( $posted['add_to_existing_group'] ) ) {
        update_post_meta( $order_id, '_create_new_group', sanitize_text_field( $posted['add_to_existing_group'] ) );            
        }    

        // Check if there is user input and save
    if( isset( $posted['create_new_group'] ) ) {
        update_post_meta( $order_id, '_create_new_group', sanitize_text_field( $posted['create_new_group'] ) );//
    } 
}
add_action( 'woocommerce_checkout_update_order_meta', 'jm_save_extra_checkout_fields', 10, 2 );

有人有任何建议吗?

1 个答案:

答案 0 :(得分:0)

假设对wc_add_notice()的调用导致退出执行路径,您可以尝试以下操作:

$blnShowFirstNotice = false;
$blnShowSecondNotice = false;

// check if user input is in array
if ($newgroupname) 
{
    if( in_array($newgroupname, $groupnames ) ) 
    {
       $blnShowFirstNotice = true;
    }
}
// check if user input is in array 
if ($existing_groupname) 
{
    if( !in_array($existing_groupname, $groupnames ) ) 
    {
        $blnShowSecondNotice = true;
    }
}

if($blnShowFirstNotice==true && $blnShowSecondNotice==false)
{
    wc_add_notice( __( 'Group name already taken.' ), 'error' );
}
else if($blnShowFirstNotice==false && $blnShowSecondNotice==true)
{           
    wc_add_notice( __( 'Group name does not exist.' ), 'error' );
}
else if($blnShowFirstNotice==true && $blnShowSecondNotice==true)
{
    wc_add_notice( __( 'Group name already taken.' . 'Group name does not exist.' ), 'error' );
}