Search code examples
phpwordpresscontact-form-7

How do I check if a WPCF7 field is null within WPCF7_Submission?


I'm creating a function to hook into wpcf7_mail_sent to save the submission of a Contact Form 7 form to a json file. I'm getting the submission to the form with the following code.

$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();

if ( $submission ) {
  // The rest of the code goes in here
}

Then I have an array with output data, where I store everything before converting it to json, like this.

$output = [
  'name' => $data['name']
]

Now I also have optional fields. I put all of those in an array, to loop through it and see it they're empty or not. But somehow this is not working.

$optional_fields = ['subject', 'phone'];
foreach ( $optional_fields as $optional_field ) {
  if ( isset($data[$optional_field]) ) {
    array_push( $output[$optional_field], $data[$optional_field] );
  } 
}

No matter if I try isset(), != null or just the example above, I always get ALL optional fields in my output, also the ones where the value is null. How can I filter out the unrequited fields?


Solution

  • I'm unsure if i got this correctly but since your posted data is here:

    $data = $submission->get_posted_data();
    

    why you loop over this:

    $optional_fields = ['subject', 'phone'];
    foreach ( $optional_fields as $optional_field ) {
    ...
    

    to check if data is empty or not? Shouldn't that be:

    $data = $submission->get_posted_data();
    $optional_fields = ['subject', 'phone'];
    foreach ( $optional_fields as $optional_field ) {
        if ( isset($data[$optional_field]) && !empty($data[$optional_field]) ) {
            array_push( $output[$optional_field], $data[$optional_field] );
        }
    }
    

    Edited1:

    Have you tried to var_dump the $data var and see which values you actually receive? because that if isset && !empty should be more then enough to filter out the undesidered values.

    You have another fallback option which is something described here: Remove empty array elements

    Sidenote for performance optimization: https://www.php.net/array-push going with array[] =.... is faster then array_push