Home > other >  How do I store user input as a variable and display it within echo for a custom wordpress plugin?
How do I store user input as a variable and display it within echo for a custom wordpress plugin?

Time:02-08

I'm relatively new to php and WordPress development and can't get the following code to work:

<?php
function addContent(){
    echo '<input type="text" name="firstname">';
    echo '<input type="submit" value="Submit">';
           
    $firstname = $_GET["firstname"];
    
    echo "<p> You wrote: $firstname </p>";
}

add_shortcode('addContent', 'addContent');
?>

If I manually assign a string to $firstname it shows fine, so the problem is in assigning the variable, which I'm having trouble with.

Thanks

CodePudding user response:

To send input data you must add <form> ...inputs...</form> so your code should looks like this

<?php
add_shortcode('addContent', 'addContent');

function addContent(){
    echo '<form method="GET">'; // printing form tag
    echo '<input type="text" name="firstname">';
    echo '<input type="submit" name="send_btn" value="Submit">';
    echo '</form>';

    if (isset($_GET['send_btn'])) { // checking is form was submitted  then accessing to value
        $firstname = $_GET['firstname'];

        echo "<p> You wrote: $firstname </p>";
    }
    
}


  •  Tags:  
  • Related