您的代码有很多错误。例如,您应该在内部定义global $current_user
, 不在外面。其他错误,您使用$query_vals
未定义该变量的函数外部的变量。无论如何,我会使用这个函数wp_get_current_user()
之前不需要调用的init action hook.
例如,如果要将POST字符串用作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;
}
为了以更具体的方式帮助您,您应该告诉我们您将在哪里使用POST字符串和上下文。
使用WP HTTP API将用户数据发送到服务器的基本示例(当您需要在将用户数据发送到第三方服务后获取响应正文时,请调用wpse\\u send\\u user\\u data):
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;
}
我更喜欢使用WP HTTP API,但如果要使用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;
}