WordPress中调用URL并发送POST数据的正确实现方式
在WordPress中发送POST请求的正确方式
在WordPress里发送POST请求,首选wp_remote_post()函数,比直接用curl或原生PHP的方式更适配WordPress的环境,能自动兼容代理、SSL这类配置。
基础用法示例
// 目标接口URL $target_url = 'https://example.com/api/endpoint'; // 要发送的POST数据 $post_data = [ 'key1' => 'value1', 'key2' => 'value2' ]; // 配置请求参数 $args = [ 'body' => $post_data, // 自动转为form-urlencoded格式 'timeout' => 15, // 超时时间(秒) 'redirection' => 5, 'httpversion' => '1.1', 'blocking' => true, // 同步请求,设为false可异步(但异步更推荐用WP Cron) 'headers' => [], 'cookies' => [] ]; // 发送请求 $response = wp_remote_post( $target_url, $args ); // 处理结果 if ( is_wp_error( $response ) ) { $error_msg = $response->get_error_message(); echo "请求失败:$error_msg"; } else { $response_body = wp_remote_retrieve_body( $response ); $response_code = wp_remote_retrieve_response_code( $response ); // 这里根据返回的内容做后续处理 }
发送JSON格式的POST数据
如果接口要求接收JSON格式的请求体,需要调整参数:
$target_url = 'https://example.com/api/json-endpoint'; $json_data = [ 'name' => '测试用户', 'email' => 'test@example.com' ]; $args = [ 'body' => json_encode( $json_data ), 'timeout' => 15, 'headers' => [ 'Content-Type' => 'application/json', 'Accept' => 'application/json' ] ]; $response = wp_remote_post( $target_url, $args );
注意事项
- 不要直接使用
file_get_contents()或者原生curl,WordPress的HTTP API(wp_remote_post()所属系列)已经封装了底层实现,能更好处理各类异常情况。 - 如果需要异步发送请求,不建议直接把
blocking设为false,更推荐用WP Cron或专门的异步任务插件,避免请求中断导致数据丢失。
内容的提问来源于stack exchange,提问作者larshetfield
相关产品推荐
相关产品推荐

