0

I use below code snippet in woocommerce and it creates php error. How I can solve it?

"[09-Nov-2022 07:55:09 UTC] PHP Warning: Undefined array key "confirm_email" in /srv/htdocs/wp-content/themes/generatepress_child/functions.php on line 846"

       /**
* Snippet Name:     WooCommerce Confirm Email On Registration Form
* Snippet Author:   ecommercehints.com
*/

// Create the field and display it on the registraiton form
add_action('woocommerce_register_form', 'ecommercehints_registraion_form_confirm_email_field');
function ecommercehints_registraion_form_confirm_email_field() {
   woocommerce_form_field(
      'confirm_email',
      array(
         'type'        => 'text',
         'required'    => true,
         'label'       => 'E-posta adresi tekrar',
     ),
      (isset($_POST['confirm_email']) ? $_POST['confirm_email'] : '')
  );
}

// Show an error message if the confirm email field is empty or doesn't match the billing email field
add_action('woocommerce_register_post', 'ecommercehints_confirm_email_field_validation', 10, 3);
function ecommercehints_confirm_email_field_validation($username, $email, $errors) {
   if (empty($_POST['confirm_email'])) {
      $errors->add('confirm_email_error', 'Lütfen e-posta adresinizi iki alana da girin!');
   }
   if ( $email !== $_POST['confirm_email'] ) {
   $errors->add('confirm_email_error', 'Girdiğiniz e-posta adresleri birbiri ile aynı değil!');
   }
}
roadlink
  • 91
  • 6

1 Answers1

0

Does your code contain line 846? There is no array key in your example called confirm_email, only billing_confirm_email. But anyway, you need to plan for the possibility that the key may not be defined. In PHP 7+ you can do this using the null coalescing operator ?? when you need to get the value of an array key:

$confirm_email_address = $_POST['billing_confirm_email'] ?? '';
Shoelaced
  • 846
  • 5
  • 27
  • Hi, Thanks for your suggestion. I have checked line 846 and found that it is different piece of code. Thus, I updated first message. This is line 846 : if ( $email !== $_POST['confirm_email'] ) { – roadlink Nov 11 '22 at 08:05
  • Cool, but my answer is still how you fix it. – Shoelaced Nov 11 '22 at 10:54
  • Thanks, So I will change this; (isset($_POST['confirm_email']) ? $_POST['confirm_email'] : '') to this (isset($_POST['confirm_email']) ? $_POST['confirm_email'] ?? '') Right? – roadlink Nov 12 '22 at 11:53
  • Ah, no that one should be fine. I think it would be this one: `if ( $email !== $_POST['confirm_email'] ) {` should be `if ( $email !== ( $_POST['confirm_email'] ?? '' ) ) {`. But I'm not positive. Which line is 846? – Shoelaced Nov 12 '22 at 17:54
  • Solved as below. if ( $email !== $_POST['confirm_email'] ) { to elseif ( $email !== $_POST['confirm_email'] ) { – roadlink Nov 14 '22 at 16:12