0

I am looking for a good way to send data from one WordPress to another.

Setup: WP1: Frontend, form to submit data. WP2: Backend, receives data and processes it.

So in WP1 users just use a form to submit data. This data should be transferred to WP2. In WP2 the data is being processed (Custom Posts are created, post meta is being added, a user is created ...).

How can I submit all the data from WP1 to WP2?

I thought about using a GET request to "forward" the form data from WP1 to WP2.

Another way could be to use the REST API to transfer the data - but I struggle with that because the processing should happen at WP2 not at WP1.

Can you help me with what is the best way to simply send the form data and trigger processing at WP2?

0

I solved it with mmm's hint and created a simple custom REST endpoint.

WP1 (Frontend, sending the data):

function send_form_data_to_backend($form_values) {

    // add secret-key
    $form_values['secret_key'] = "abcde123";

    $url = 'http://backend.example.com/wp-json/example/v1/save/';
    $response = wp_safe_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 15,
        'redirection' => 5,
        'blocking' => true,
        'headers' => array(),
        'body' => $form_values,
        'cookies' => array()
        )
    );

    if ( is_wp_error( $response ) ) {
       $error_message = $response->get_error_message();
       echo "Something went wrong: $error_message";
    } else {
       echo 'Response:<pre>';
       print_r( $response );
       echo '</pre>';
    }
}

WP2 (Backend, receiving the data):

add_action( 'rest_api_init', 'post_request' );

function post_request() {

    register_rest_route( 'example/v1', '/save/', array(
                'methods' => 'POST',
                'callback' => 'rest_function')
    );
}


/*
 * REST Function
 */
function rest_function( $data ) {

    if ( $data['secret_key'] == "abcde123" ) {

        $msg = example_main_form_processing( $data );

        return $msg;

    } else {
        return "Wrong Key.";
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.