wordpressfunctionhttp-post-vars

Unable to get var value inside function


I am trying to get field_1 value into the input text and I tried this code but it doesn't work.

function bbg_add_reg_field() {
  $field_1= $_POST["signup_username"];  
  echo '<input name="field_1" id="field_1" value="$field_1" type="text">';  
}
add_action( 'bp_before_registration_submit_buttons', 'bbg_add_reg_field' );

The echo value shown inside the input text is $field_1

The value should be a name, say for example peter.


Solution

  • In PHP you can interpolate a string (add variables to a string with $var) only when it is a double quoted string.

    From the PHP Documentation

    // Outputs: Variables do not $expand $either
    echo 'Variables do not $expand $either';
    

    Instead you could do this

    echo '<input name="field_1" id="field_1" value="' . $field_1 . '" type="text">';
    

    oh and don't forget htmlspecialchars

    echo '<input name="field_1" id="field_1" value="' . htmlspecialchars($field_1) . '" type="text">';
    

    You could also achieve the same using PHP Heredoc. Which goes like this

    echo <<<EOF
    <input name="field_1" id="field_1" value="$field_1" type="text">
    EOF;