2

I have created a contact form (with a lot of help from you guys here) and I want to be able to use it on pages and in text widgets via a shortcode (for sidebars etc). It works perfectly on both with the exception of when the form is submitted, I get Illegal string offset in just the sidebar widget form. The page form works fine however. What I am trying to do is pull the 'name' field from the form to echo the users name when the form submits successfully. The line of code that throws the warning is this:

echo '<p>Thank you for contacting us '.$_POST['cf-name'].', a member of our team will be in touch with you shortly.</p>';

I also tried:

echo '<p>Thank you for contacting us '.(isset($_POST[ 'cf-name' ])).', a member of our team will be in touch with you shortly.</p>';

Using the second example removes the warning, but neither display the users name on form subbmission and that latter option displays 1 in the page contact form when before it was working. Any ideas how to fix this?

The full function is:

function my_form_message()
{
    global $errors;
    if (is_wp_error($errors) && empty($errors->errors)) {
        echo '<section class="alertbox-success">';
        echo '<div class="cf-success">';
        echo '<p>Thank you for contacting us '.$_POST['cf-name'].', a member of our team will be in touch with you shortly.</p>';
        echo '</div>';
        echo '</section>';

    //Empty $_POST because we already sent email
    $_POST = '';
    } else {
        if (is_wp_error($errors) && !empty($errors->errors)) {
            $error_messages = $errors->get_error_messages();
            foreach ($error_messages as $k => $message) {
                echo '<section class="alertbox-error">';
                echo '<div class="cf-error '.$k.'">';
                echo '<p>'.$message.'</p>';
                echo '</div>';
                echo '</section>';
            }
        }
    }
}

Don't know if that helps or not. Any ideas would be greatly appreciated. Thanks in advance

EDIT: This is the full warning:

/Applications/MAMP/htdocs/centenary-framework/wp-content/themes/cent_framework/assets/inc/core/contact-form.php on line 113

Notice: Uninitialized string offset: 0 in /Applications/MAMP/htdocs/centenary-framework/wp-content/themes/cent_framework/assets/inc/core/contact-form.php on line 113
Thank you for contacting us , a member of our team will be in touch with you shortly.

EDIT:

Full code:

<?php

// Form markup
 function cf_form_code()
 {
     ?>
<div class="cf-contact-form">
 <form action="<?php esc_url($_SERVER['REQUEST_URI']);
     ?>" method="post">
   <p>
     <input type="text" name="cf-name" placeholder="Name (required)" pattern="[a-zA-Z0-9 ]+" value="<?php isset($_POST['cf-name']) ? esc_attr($_POST['cf-name']) : '';
     ?><?php if (isset($_POST['cf-name'])) {
    echo htmlentities($_POST['cf-name']);
}
     ?>" size="40" />
   </p>
   <p>
     <input type="email" name="cf-email" placeholder="Email (required)" value="<?php isset($_POST['cf-email']) ? esc_attr($_POST['cf-email']) : '';
     ?><?php if (isset($_POST['cf-email'])) {
    echo htmlentities($_POST['cf-email']);
}
     ?>" size="40" />
   </p>
   <p>
     <input type="tel" name="cf-tel" placeholder="Telephone" pattern="^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$" value="<?php isset($_POST['cf-tel']) ? esc_attr($_POST['cf-tel']) : '';
     ?><?php if (isset($_POST['cf-tel'])) {
    echo htmlentities($_POST['cf-tel']);
}
     ?>" size="40" />
   </p>
   <p>
     <textarea class="cf-message" rows="10" cols="35" name="cf-message" placeholder="Message (required)" onkeyup="adjust_textarea(this)"><?php isset($_POST['cf-message']) ? esc_attr($_POST['cf-message']) : '';
     ?><?php if (isset($_POST['cf-message'])) {
    echo htmlentities($_POST['cf-message']);
}
     ?></textarea>
   </p>
   <p><input type="text" name="content" id="content" value="" class="hpot" /></p>
   <p><input type="submit" name="cf-submitted" value="Send"/></p>
 </form>
</div>
 <?php

 }

// Form validation
 function cf_validate_form()
 {
     $errors = new WP_Error();

     if (isset($_POST[ 'content' ]) && $_POST[ 'content' ] !== '') {
         $errors->add('bot', 'Sorry, this field should not be filled in. Robots only');
     }

     if (isset($_POST[ 'cf-name' ]) && $_POST[ 'cf-name' ] == '') {
         $errors->add('name_error', 'Please fill in a valid name.');
     }

     if (isset($_POST[ 'cf-email' ]) && $_POST[ 'cf-email' ] == '') {
         $errors->add('email_error', 'Please fill in a valid email.');
     }

     if (isset($_POST[ 'cf-message' ]) && $_POST[ 'cf-message' ] == '') {
         $errors->add('message_error', 'Please fill in a valid message.');
     }

     return $errors;
 }

// Form delivery
 function deliver_mail($args = array())
 {

  // This $default array is a way to initialize some default values that will be overwritten by our $args array.
  // We could add more keys as we see fit and it's a nice way to see what parameter we are using in our function.
  // It will only be overwritten with the values of our $args array if the keys are present in $args.
  // This uses WP wp_parse_args() function.
  $defaults = array(
    'name' => '',
    'email' => '',
    'tel' => '',
    'message' => '',
    'to' => get_option('admin_email'), // get the administrator's email address
  );

     $args = wp_parse_args($args, $defaults);

     $headers = "From: {$args['name']}  <{$args['email']}>"."\r\n";

  // Send email returns true on success, false otherwise
  if (wp_mail($args['to'], $args['tel'], $args['message'], $headers)) {
      return;
  } else {
      return false;
  }
 }

// Form sanitize
function cf_sanitize_field($input)
{
    return trim(stripslashes(sanitize_text_field($input)));
}

// Form succsess message
function cf_form_message()
{
    global $errors;
    if (is_wp_error($errors) && empty($errors->errors)) {
        echo '<section class="alertbox-success">';
        echo '<div class="cf-success">';
        echo '<p>Thank you for contacting us '.$_POST['cf-name'].', a member of our team will be in touch with you shortly.</p>';
        echo '</div>';
        echo '</section>';

    //Empty $_POST because we already sent email
    $_POST = '';
    } else {
        if (is_wp_error($errors) && !empty($errors->errors)) {
            $error_messages = $errors->get_error_messages();
            foreach ($error_messages as $k => $message) {
                echo '<section class="alertbox-error">';
                echo '<div class="cf-error '.$k.'">';
                echo '<p>'.$message.'</p>';
                echo '</div>';
                echo '</section>';
            }
        }
    }
}

// Form shortcode
add_shortcode('contact_form', 'cf_contact_form');
function cf_contact_form()
{
    ob_start();

    cf_form_message();
    cf_form_code();

    return ob_get_clean();
}

// Error validation
add_action('init', 'cf_cf_form');
function cf_cf_form()
{
    if (isset($_POST['cf-submitted'])) {
        global $errors;
        $errors = cf_validate_form();
        if (empty($errors->errors)) {
            $args = array(
         'name' => cf_sanitize_field($_POST['cf-name']),
         'email' => cf_sanitize_field($_POST['cf-email']),
         'tel' => cf_sanitize_field($_POST['cf-tel']),
         'message' => cf_sanitize_field($_POST['cf-message']),
       );
            deliver_mail($args);
        } else {
            return $errors;
        }
    }
}

closed as off-topic by Mark Kaplun, bueltge, kaiser Sep 10 '16 at 20:09

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions that are too localized (such as syntax errors, code with restricted access, hacked sites, hosting or support issues) are not in scope. See how do I ask a good question?" – Mark Kaplun, bueltge, kaiser
If this question can be reworded to fit the rules in the help center, please edit the question.

  • The error specifically calls out line 113 in contact-form.php - which line is that? – MadtownLems Aug 25 '16 at 13:11
  • It's the very first line of code I posted echo '<p>Thank you for contacting us '.$_POST['cf-name'].', a member of our team will be in touch with you shortly.</p>'; – user53340 Aug 25 '16 at 13:12
  • 1
    don't use globals, and when you use them, always use a namespace or prefix them. Your problem is most likely with some strange value in $errors – Mark Kaplun Aug 25 '16 at 13:28
  • Sorry, I'm not to sure what you mean prefix them. cf- is the prefix I have used for the form fields. Should other things be prefixed? – user53340 Aug 25 '16 at 13:31
  • This is a plain PHP problem. Check variables and array members before using them – no one will be able to fix that and give you a better advice. – kaiser Sep 10 '16 at 20:08
2

Uninitialized string offset: 0

This error is showing because there is an empty value. Try checking if the value is !empty() (not empty) first. Here's the source code you provide in your question with my update.

function cf_form_message() {
    global $errors;
    if ( is_wp_error( $errors ) && empty( $errors -> errors ) ) {
        ?>
        <section class="alertbox-success">
            <div class="cf-success">
                <p>Thank you for contacting us <?php if ( isset( $_POST['cf-name'] ) && !empty( $_POST['cf-name'] ) ) { echo $_POST['cf-name']; } else { echo 'NO_NAME'; } ?>, a member of our team will be in touch with you shortly.</p>
            </div>
        </section>
        <?php
        //Empty $_POST because we already sent email
        $_POST = '';
    }
    else {
        if ( is_wp_error( $errors ) && !empty( $errors -> errors ) ) {
            $error_messages = $errors -> get_error_messages();
            foreach ( $error_messages as $k => $message ) {
                ?>
                <section class="alertbox-error">
                    <div class="cf-error <?php echo $k; ?>">
                        <p><?php echo $message ?></p>
                    </div>
                </section>
                <?php
            }
        }
    }
}
  • Thanks for your answer. This returns syntax error unexpected 'if' I copied it directly. Do I need yo maybe use the <?php ?> tags instead of appending the php? I've had errors like this before when using echo with html and php. Thanks – user53340 Aug 26 '16 at 13:05
  • @user53340 Yeah, I see that. I've updated the code by closing the <?php ?> tags and then reopening them. Let me know if my update work – Ethan Jinks O'Sullivan Aug 26 '16 at 13:12
  • unexpected '}' now. This is why I love php lol should I try removing the {} ? Thanks again =) – user53340 Aug 26 '16 at 13:15
  • hmm no that gives the following uncaught Error: Call to undefined function cf_form_message() – user53340 Aug 26 '16 at 13:16
  • Would it be easier if I posted the entire code so you can test? I don't want to take liberties, as I appreciate you taking your time to look at this. But I thought it may help? – user53340 Aug 26 '16 at 13:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.