0

I have to wp site ex1.com and ex2.com, at ex1.com i have created a post and i want to send it to ex2.com with Title, content, custom fields, tags, category with a form submit button at edit window. I created code for rest api remote push but now i'm stuck where is the problem in the code.

    add_meta_box('custom_post_push', 'Push Post Data to Remote Site', 'render_custom_meta_box', 'post', 'normal', 'default');
}

function render_custom_meta_box() {
    echo '<form method="post">';
    // Add form fields here
    echo '<input type="submit" name="push_to_remote_site" value="Push to Remote Site">';
    echo '</form>';

    if (isset($_POST['push_to_remote_site'])) {
        // Code for pushing data to the remote site when the button is clicked

        $post_id = get_the_ID();

        // Retrieve post data, build the array, and encode it to JSON format as before
        $post_title = get_the_title($post_id);
        $content = get_the_content($post_id);
        $categories = wp_get_post_categories($post_id, array('fields' => 'names'));
        $tags = wp_get_post_tags($post_id, array('fields' => 'names'));
        $custom_fields = get_post_custom($post_id);

        $post_data = array(
            'post_title' => $post_title,
            'post_content' => $content,
            'categories' => $categories,
            'tags' => $tags,
            'status' => 'draft',
            'custom_fields' => $custom_fields, // Include all custom fields.
        );

        // Convert the post data to JSON format
        $post_data = json_encode($post_data);

        // Define your remote website URL and authentication credentials
        $remote_url = 'https://www.ex2.com/wp-json/wp/v2/posts';
        $login = 'username';
        $password = 'xxxx xxxx xxxx xxxx xxxx xxxx';

        // Send the post data to the remote website
        $response = wp_remote_post(
            $remote_url,
            array(
                'headers' => array(
                    'Authorization' => 'Basic ' . base64_encode("$login:$password"),
                    'Content-Type' => 'application/json',
                ),
                'body' => $post_data,
            )
        );

        if (is_wp_error($response)) {
            echo "Success";
        } else {
            echo "Error!";
        }
    }
}

add_action('add_meta_boxes', 'add_custom_meta_box');```

2 Answers 2

2

From the code you've provided, it seems like you're on the right track. However, there are a few potential issues that might be causing problems:

  1. Form Submission: The form submission might not be working as expected because WordPress admin area already has a form for post editing. When you add another form inside it, it might not work correctly. Instead of creating a new form, you can add a custom submit button to the existing post edit form.

  2. Data Preparation: The REST API expects the data in a specific format. For example, categories and tags should be arrays of term IDs, not names. Also, the custom fields should be an array of meta keys and values.

  3. Error Handling: Your error handling seems to be reversed. is_wp_error($response) will return true if there was an error, not if the request was successful.

  4. Authentication: The Basic Auth method you're using might not be enabled on the remote site. You need to ensure that the Basic Auth plugin is installed and activated on the remote site.

Here's a revised version of your code:

function render_custom_meta_box() {
    // Add a custom submit button to the existing post edit form
    echo '<input type="submit" name="push_to_remote_site" value="Push to Remote Site">';

    if (isset($_POST['push_to_remote_site'])) {
        // Code for pushing data to the remote site when the button is clicked

        $post_id = get_the_ID();

        // Retrieve post data, build the array
        $post_title = get_the_title($post_id);
        $content = get_post_field('post_content', $post_id);
        $categories = wp_get_post_categories($post_id);
        $tags = wp_get_post_tags($post_id, array('fields' => 'ids'));
        $custom_fields = get_post_custom($post_id);

        $post_data = array(
            'title' => $post_title,
            'content' => $content,
            'categories' => $categories,
            'tags' => $tags,
            'status' => 'draft',
            'meta' => $custom_fields, // Include all custom fields.
        );

        // Convert the post data to JSON format
        $post_data = wp_json_encode($post_data);

        // Define your remote website URL and authentication credentials
        $remote_url = 'https://www.ex2.com/wp-json/wp/v2/posts';
        $login = 'username';
        $password = 'password';

        // Send the post data to the remote website
        $response = wp_remote_post(
            $remote_url,
            array(
                'headers' => array(
                    'Authorization' => 'Basic ' . base64_encode("$login:$password"),
                    'Content-Type' => 'application/json',
                ),
                'body' => $post_data,
            )
        );

        if (is_wp_error($response)) {
            echo "Error!";
        } else {
            echo "Success";
        }
    }
}

add_action('add_meta_boxes', 'add_custom_meta_box');

Remember to replace 'username' and 'password' with your actual username and password. Also, ensure that the REST API is enabled on the remote site and that it allows creating posts.

1
  • It's not pushing post to remote website and even not showing any message alert, after click on push to remote site the update button also loading and print the post has been updated. BTW current post status is published and trying to push it as draft to ex2.com
    – Puneet
    Commented Oct 19, 2023 at 16:51
0

Sounds like you're facing a couple of challenges. Let's address them step-by-step:

  1. Form Submission Issue: The WordPress post editor already has its own form. When you add a custom form or button inside it, things can get a bit wonky. Your "Push to Remote Site" button might be causing the entire post editor form to submit, which explains why you see the "Post has been updated" message.

  2. Handling Responses: To debug what might be going wrong, it would be super helpful to get the exact error message from the $response.

  3. Draft Status: If the current post status is "published" and you're trying to push it as a "draft", you have to ensure the user role on ex2.com has the capability to publish posts. Otherwise, it might fail.

Here's an approach to debug and hopefully fix the problem:

  1. Adjust Your Custom Button: Let's use JavaScript to handle the click event of your custom button. This way, you can make the API call without causing the main post form to submit.
function render_custom_meta_box() {
    // Add a custom submit button
    echo '<button type="button" id="push-to-remote-btn">Push to Remote Site</button>';
    echo '<div id="push-response"></div>'; // A place to display the result

    // Include some JavaScript to handle the button click
    ?>
    <script type="text/javascript">
        document.getElementById('push-to-remote-btn').addEventListener('click', function() {
            var data = {
                'action': 'push_to_remote_site',
                'post_id': <?php echo get_the_ID(); ?>
            };

            jQuery.post(ajaxurl, data, function(response) {
                document.getElementById('push-response').innerHTML = response;
            });
        });
    </script>
    <?php
}

1.Handle the AJAX in PHP:

function push_to_remote_site_callback() {
    $post_id = $_POST['post_id'];

    // ... (your code to prepare the post data)

    // Send the post data to the remote website
    $response = wp_remote_post(
        $remote_url,
        array(
            'headers' => array(
                'Authorization' => 'Basic ' . base64_encode("$login:$password"),
                'Content-Type' => 'application/json',
            ),
            'body' => $post_data,
        )
    );

    if (is_wp_error($response)) {
        echo "Error: " . $response->get_error_message();
    } else {
        echo "Success";
    }

    wp_die(); // this is required to terminate immediately and return a proper response
}

add_action('wp_ajax_push_to_remote_site', 'push_to_remote_site_callback');

Error Handling: In the AJAX callback, I'm outputting the error message from $response directly. This should give you a clearer idea of what might be wrong. Remember, it's super important to ensure:

Basic Auth is enabled on ex2.com. The user role associated with the 'username' and 'password' you're using has the proper capabilities. CORS headers are set correctly if the domain ex1.com is not whitelisted on ex2.com. Give this a go and see if it brings you closer to a solution! 🛠️

P.S. Always take a backup of your functions or custom code before trying out any changes. Safety first! Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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