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');```