There are 2 sites from the first one you need to send an array of POST, and on the second one you accept and process it, I do this: On the site " http://test1.com " I send the POST data to " http://test2.com " by this method

$url = 'http://test2.com'; $params = array( 'data_send' => $data_send, //$_POST['data_send'] ); file_get_contents($url, false, stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => http_build_query($params) ) ))); 

On " http://test2.com " in the topic function.php I accept:

  if(isset($_POST['data_send'])){ var_dump($_POST['data_send']);} 

But there is nothing, on pure PHP such an example worked for me, can someone tell me how to do this correctly on wordpress

  • and where did they get that function.php should accept your request? if you want to distort this method (:)) and get data, specify the full path to the file $ url = ' test2.com/wp-content \ themes \ your_theme \ function.php'; - but what you want to do is horror - Arsen
  • @Arsen tell me how not to do something awful, set on the right path? - Vitaliy
  • If you say what data you want to get on the second site and where you want to use - I will help)) - Arsen
  • @Arsen that method does not work leads to the error 'Call to undefined function get_template_directory ()' :( In general, the situation is I get an array of data from the database and I need to transfer this data to the second site, on the second site the main thing is to catch this post somehow I'll figure it out) - Vitaliy

1 answer 1

Send a request to the test2.com website:

 $body = array( 'data_send' => $data_send, ); $result = wp_remote_post( 'http://test2.com', array( 'method' => 'POST', 'redirection' => 1, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $body, 'cookies' => array(), ) ); if ( is_wp_error( $result ) ) { // вернуть ошибку } $body = $result['body']; $body_array = json_decode( $body ); $success = $body_array->success; if ( ! $success ) { // вернуть ошибку } $data = $body_array->data; // Это ответ от test2.com 

Receive, process the request and send a response on the test2.com website:

 add_action( 'init', 'get_request' ); function get_request() { if ( isset( $_POST[ 'data_send' ] ) ) { $data = $_POST[ 'data_send' ]; // Обработка данных, // установка флага $result // создание (если нужно) массива возвращаемых данных $data if ( $result ) { wp_send_json_success( $data ); } else { wp_send_json_error(); } } } 
  • $ _POST ['data_send'] does not come to functions.php, $ body_array is for some reason empty, and if (! $ Success) is an error - Vitaliy
  • Well, like everything works, thanks - Vitaliy