Your code has a lot of errors. For example, inside you should define the global $current_user
, not outside. Other error, you use $query_vals
variable outside the function where that variable is not defined. Anyway, I would use the function wp_get_current_user()
which have not to be called before init action hook.
For example, if you are going to use the POST string as data for javascript:
add_action( 'wp_enqueue_scripts', 'wpse_scripts' );
function wpse_scripts() {
$user_fields = wpse_get_current_user_info();
$postdata = http_build_query( $user_fields );
wp_localize_script( 'my_script', 'my_script_data', $postdata );
}
function wpse_get_current_user_info() {
$current_user = wp_get_current_user();
$current_user_info = array(
'firstname' => $current_user->user_firstname,
'lastname' => $current_user->user_lastname,
//Add the rest of info you need
//In the forman key => value
);
return $current_user_info;
}
In order to help you in a more specific way you should tell us where are you going to use the POST string and the context.
Basic example to send the user data to a server using WP HTTP API (Call wpse_send_user_data when you need to get the response body after sending the user data to the third party service):
function wpse_send_user_data() {
//You should check here if the request should be done
//if( $some_control == true ) return;
$uerdata = wpse_get_current_user_info();
$args = array( 'method' => 'POST', 'body' => $uerdata );
$request = wp_remote_request( 'http://www.example.com', $args )
$response = wp_remote_retrieve_body($request);
return $response;
}
function wpse_get_current_user_info() {
$current_user = wp_get_current_user();
$current_user_info = array(
'firstname' => $current_user->user_firstname,
'lastname' => $current_user->user_lastname,
//Add the rest of info you need
//In the forman key => value
);
return $current_user_info;
}
I prefer use WP HTTP API but if you want to use cURL:
function wpse_send_user_data() {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/");
curl_setopt($ch, CURLOPT_POST, 1);
// Get userinfo array and set as POST fields
$uerdata = wpse_get_current_user_info();
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $uerdata ));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
}
function wpse_get_current_user_info() {
$current_user = wp_get_current_user();
$current_user_info = array(
'firstname' => $current_user->user_firstname,
'lastname' => $current_user->user_lastname,
//Add the rest of info you need
//In the forman key => value
);
return $current_user_info;
}