php - How to pass username into form that sends data to database

admin2025-01-07  4

I am trying to pass username to database through form:

[insert_php]
$current_user= wp_get_current_user();
$id= $current_user->user_login; 
[/insert_php]


<input type="hidden" name="id" value="[insert_php]$id[/insert_php]">

But it doesn't get through, the rest of visible inputs do go through though.

I am trying to pass username to database through form:

[insert_php]
$current_user= wp_get_current_user();
$id= $current_user->user_login; 
[/insert_php]


<input type="hidden" name="id" value="[insert_php]$id[/insert_php]">

But it doesn't get through, the rest of visible inputs do go through though.

Share Improve this question asked Aug 8, 2014 at 18:18 AcidonAcidon 1471 gold badge3 silver badges12 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 0

If you want to output the $id, you need to echo.
Also be sure to use esc_attr() as a good security practice.

<input type="hidden" name="id" value="[insert_php]echo esc_attr( $id );[/insert_php]">

In addition, as was noted in another answer, you're calling it an 'id', but you're actually using the login (username). If all you need is the numeric ID, use get_current_user_id().

<input type="hidden" name="id" value="[insert_php]echo esc_attr( get_current_user_id() );[/insert_php]">

Really, the answer by @jaswrks will work, if you are using a shortcode to run code via an edited page.

But, this is back to front way of using PHP.. and you are so close to learning how to really write PHP inside WordPress, instead of via a proxy like a shortcode that allows you to write quasi-PHP in the editor..

So, what you could also try, is to edit the page template where the form appears ( or add via widgets, blocks, external functions or any of the other means available ) and add the following:

<?php

// get current user ID, with default value, if empty
$current_user_id = wp_get_current_user_id() ?? 0;

?>
<input type="hidden" name="id" value="<?php echo esc_attr( $current_user_id ); ?>">  

What you want is to use :

$id = get_current_user_id()

What the function that you are using does is get an object.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736260721a685.html

最新回复(0)