在WordPress中,你可以使用PHP来模拟POST提交的两种方法是使用wp_remote_post
函数和使用curl
库。以下是这两种方法的示例代码:
方法1:使用wp_remote_post
函数
// 创建POST数据数组 $post_data = array( 'post_title' => '这是一个示例标题', 'post_content' => '这是示例内容', 'post_status' => 'publish', ); // 发送POST请求 $response = wp_remote_post('https://yourwordpresssite.com/wpjson/wp/v2/posts', array( 'body' => json_encode($post_data), 'headers' => array('ContentType' => 'application/json'), )); // 检查响应是否成功 if (is_wp_error($response)) { echo 'POST请求失败: ' . $response>get_error_message(); } else { echo 'POST请求成功!'; }
方法2:使用curl
库
// 创建POST数据数组 $post_data = array( 'post_title' => '这是一个示例标题', 'post_content' => '这是示例内容', 'post_status' => 'publish', ); // 初始化cURL会话 $ch = curl_init('https://yourwordpresssite.com/wpjson/wp/v2/posts'); // 设置cURL选项 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); curl_setopt($ch, CURLOPT_HTTPHEADER, array('ContentType: application/json')); // 执行cURL请求 $response = curl_exec($ch); // 检查请求是否成功 if ($response === false) { echo 'POST请求失败: ' . curl_error($ch); } else { echo 'POST请求成功!'; } // 关闭cURL会话 curl_close($ch);
这两种方法都可以用来模拟POST提交到WordPress,并创建新的文章。你可以根据你的需求选择其中一种方法。不过,请确保替换示例代码中的URL和POST数据为你自己的WordPress站点信息和要提交的数据。