简体   繁体   中英

How to add username variable in wordpress post to html form?

I added this html form in my wordpress post:

    <form action="script.php" method="post">
 <p>Name: <input type="text" name="name" /></p>
 <p>Username: <input type="text" name="username" /></p>
 <p>Address: <input type="text" name="address" /></p>
 <p>Email: <input type="text" name="email" /></p>
 <p><input type="submit" /></p>
</form> 

I want add wordpress username variable (current user) instead this string in html form:

<p>Username: <input type="text" name="username" /></p>

And post all variables to my PHP script, where I get derived variables like this:

$username = $_POST['username'];

I want that the variable is set automatically by wordpress username

It's fairly straightforward. Using the wordpress APIs, you can just do this:

Call the object:

<?php $current_user = wp_get_current_user(); ?>

And then in your form:

<p>Username: <input type="text" name="'<?php echo $current_user->display_name; ?>" /></p>

Or if you just want to call the username, and not have it an input form you do it like this:

echo $current_user->display_name;

You can also get any of the other parts of the object if you like, for instance if you want their user id, and not show it, but have it submitted with their form data, use a hidden form field like so:

<p>User ID: <input type="hidden" name="'<?php echo $current_user->ID; ?>" /></p>

Having PHP evaluated right from the post edit screen is a security problem.

I recommend using a form plugin such as Gravity Forms and hooking into its API to pull in dynamic content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM