Skip to content

Instantly share code, notes, and snippets.

@hmowais
Created July 26, 2024 13:51
Show Gist options
  • Save hmowais/42aa1c0887e8ba873b142c833ff491f4 to your computer and use it in GitHub Desktop.
Save hmowais/42aa1c0887e8ba873b142c833ff491f4 to your computer and use it in GitHub Desktop.
Post Sync to other website with REST API
<?php
// Website 1
/* API for Post Sync */
function send_post_to_campus($post_id) {
if (wp_is_post_revision($post_id)) {
error_log('Skipping post revision ID: ' . $post_id);
return;
}
$post = get_post($post_id);
$categories = wp_get_post_terms($post_id, 'media_categories', array('fields' => 'slugs'));
// Log post and categories
error_log('Post ID: ' . $post->ID);
error_log('Categories: ' . print_r($categories, true));
if (in_array('in-the-news', $categories)) {
$featured_image_url = wp_get_attachment_url(get_post_thumbnail_id($post_id));
$author_id = $post->post_author; // Get the author ID
$url = 'https://WEBSITE URL/wp-json/custom/v1/sync-post';
$body = array(
'slug' => $post->post_name, // Use post slug
'title' => $post->post_title,
'content' => $post->post_content,
'featured_image' => $featured_image_url, // Send the featured image URL
'author_id' => $author_id, // Send the author ID
);
// Log request data
error_log('Request URL: ' . $url);
error_log('Request Body: ' . json_encode($body));
$response = wp_remote_post($url, array(
'method' => 'POST',
'body' => json_encode($body),
'timeout' => 45,
'headers' => array(
'Content-Type' => 'application/json',
),
));
// Log the response or error
if (is_wp_error($response)) {
error_log('Error sending POST request: ' . $response->get_error_message());
} else {
error_log('Response from CAMPUS: ' . print_r($response, true));
}
} else {
error_log('The post is not in the "in-the-news" category.');
}
}
add_action('save_post_media', 'send_post_to_campus');
<?php
// Website 2
/* API post recieve */
add_action('rest_api_init', function () {
register_rest_route('custom/v1', '/sync-post', array(
'methods' => 'POST',
'callback' => 'sync_post_callback',
'permission_callback' => '__return_true', // Adjust permissions as needed
));
});
function sync_post_callback($data) {
// Check for required fields
if (!isset($data['slug']) || !isset($data['title']) || !isset($data['content']) || !isset($data['featured_image']) || !isset($data['author_id'])) {
return new WP_Error('missing_data', 'Required data is missing', array('status' => 400));
}
// Sanitize data
$slug = sanitize_title($data['slug']);
$content = wp_kses_post($data['content']);
$title = sanitize_text_field($data['title']);
$featured_image_url = esc_url_raw($data['featured_image']);
$author_id = intval($data['author_id']); // Ensure author ID is an integer
// Validate author ID
if (!get_userdata($author_id)) {
error_log('Invalid author ID received: ' . $author_id);
$author_id = 1; // Default to a specific author ID, such as admin
}
// Check if a post with this slug already exists
$existing_posts = get_posts(array(
'post_type' => 'work',
'name' => $slug, // Use 'name' to match slug
'post_status' => 'any',
'numberposts' => 1,
));
if ($existing_posts) {
// Post exists, update it
$post_id = $existing_posts[0]->ID;
error_log('Updating post ID: ' . $post_id);
$updated_post_id = wp_update_post(array(
'ID' => $post_id,
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => $author_id, // Set the author ID
));
if (is_wp_error($updated_post_id)) {
error_log('Error updating post: ' . $updated_post_id->get_error_message());
return new WP_Error('post_update_failed', 'Failed to update post', array('status' => 500));
}
$post_id = $updated_post_id;
$action = 'updated';
} else {
// Post does not exist, create a new one
$new_post_id = wp_insert_post(array(
'post_name' => $slug,
'post_type' => 'work',
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_author' => $author_id, // Set the author ID
));
if (is_wp_error($new_post_id)) {
error_log('Error creating post: ' . $new_post_id->get_error_message());
return new WP_Error('post_creation_failed', 'Failed to create post', array('status' => 500));
}
$post_id = $new_post_id;
$action = 'created';
}
// Ensure post is published
$post_status = get_post_status($post_id);
if ($post_status !== 'publish') {
$updated_status = wp_update_post(array(
'ID' => $post_id,
'post_status' => 'publish',
));
if (is_wp_error($updated_status)) {
error_log('Error updating post status to publish: ' . $updated_status->get_error_message());
} else {
error_log('Post status updated to publish.');
}
}
// Check if the featured image already exists
if (!empty($featured_image_url)) {
// Check if the image already exists
$existing_image = get_posts(array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'meta_query' => array(
array(
'key' => '_wp_attached_file',
'value' => basename($featured_image_url),
'compare' => 'LIKE',
),
),
'numberposts' => 1,
));
if (!$existing_image) {
// Fetch the image if it does not exist
$response = wp_remote_get($featured_image_url);
if (is_wp_error($response)) {
error_log('Error fetching image: ' . $response->get_error_message());
} else {
$image_body = wp_remote_retrieve_body($response);
$image_name = basename($featured_image_url);
$upload = wp_upload_bits($image_name, null, $image_body);
if ($upload['error']) {
error_log('Error uploading image: ' . $upload['error']);
} else {
$attachment = array(
'post_mime_type' => wp_check_filetype($upload['file'])['type'],
'post_title' => sanitize_text_field(pathinfo($upload['file'], PATHINFO_FILENAME)),
'post_content' => '',
'post_status' => 'inherit',
);
// Insert the attachment into the media library
$attachment_id = wp_insert_attachment($attachment, $upload['file'], $post_id);
if (!is_wp_error($attachment_id)) {
// Generate attachment metadata
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attachment_id, $upload['file']);
wp_update_attachment_metadata($attachment_id, $attach_data);
// Set as featured image
set_post_thumbnail($post_id, $attachment_id);
error_log('Featured image set for post ID: ' . $post_id);
} else {
error_log('Error inserting attachment: ' . $attachment_id->get_error_message());
}
}
}
} else {
$attachment_id = $existing_image[0]->ID;
set_post_thumbnail($post_id, $attachment_id);
error_log('Featured image already exists, set for post ID: ' . $post_id);
}
}
// Get the term ID for the 'in-the-news' slug in the 'work_categories' taxonomy
$term = get_term_by('slug', 'in-the-news', 'work_categories');
if ($term) {
// Assign the term ID to the post
$term_assign = wp_set_post_terms($post_id, array($term->term_id), 'work_categories');
// Log the assignment for debugging
if (is_wp_error($term_assign)) {
error_log('Error assigning category: ' . $term_assign->get_error_message());
} else {
error_log('Post ' . $action . ': Assigned categories: ' . print_r(wp_get_post_terms($post_id, 'work_categories', array('fields' => 'slugs')), true));
}
} else {
error_log('Term "in-the-news" not found in taxonomy "work_categories".');
}
return new WP_REST_Response('Post ' . $action . ' and category assigned', 200);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment