两个 if 语句,两者都单独工作但不一起工作,PHP


Two if statements, both working separately but not together, PHP

我在WordPress中工作,用于Woo商务的扩展。我在结帐页面上有两个自定义字段,当用户输入值存在于数据库中时,它们都是保存和报告通知,而当它不存在时,它们又是另一个。这两个字段都独立工作,但是当两个字段都处于活动状态时,无论输入哪个字段,只有第一个条件会引发错误。

我正在使用的代码

// 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 );

有人有什么建议吗?

假设对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' );
}