Created
April 18, 2023 20:45
-
-
Save jonasduerto/d0282c28c2bd83748a027f5163534c87 to your computer and use it in GitHub Desktop.
Create a post into and Send via AJAX to another WordPress and insert it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // This code should be added to functions.php or a custom plugin | |
| /** | |
| * Send post via AJAX to another WordPress and insert it | |
| */ | |
| function cwpai_send_post_to_other_wordpress() { | |
| // Check if it's a post being created | |
| if ( isset( $_POST['post_id'] ) ) { | |
| // Get post data | |
| $post_id = $_POST['post_id']; | |
| $post = get_post( $post_id ); | |
| // Create post array with necessary fields | |
| $post_data = array( | |
| 'post_title' => $post->post_title, | |
| 'post_content' => $post->post_content, | |
| 'post_excerpt' => $post->post_excerpt, | |
| 'post_status' => $post->post_status, | |
| 'post_author' => $post->post_author, | |
| 'post_type' => $post->post_type, | |
| 'post_date' => $post->post_date, | |
| 'post_date_gmt' => $post->post_date_gmt | |
| ); | |
| // Send AJAX request to other WordPress with post data | |
| $url = 'http://www.example.com/wp-admin/admin-ajax.php'; | |
| $data = array( | |
| 'action' => 'cwpai_insert_post', | |
| 'post_data' => $post_data, | |
| ); | |
| $args = array( | |
| 'body' => $data, | |
| ); | |
| $response = wp_remote_post( $url, $args ); | |
| // Check if response is successful and insert post | |
| if ( !is_wp_error( $response ) && $response['response']['code'] == 200 ) { | |
| $post_id = wp_insert_post( $post_data ); | |
| wp_publish_post( $post_id ); | |
| } | |
| } | |
| } | |
| add_action( 'save_post', 'cwpai_send_post_to_other_wordpress' ); | |
| /** | |
| * AJAX action to insert post into WordPress | |
| */ | |
| function cwpai_insert_post() { | |
| $post_data = $_POST['post_data']; | |
| $post_id = wp_insert_post( $post_data ); | |
| wp_send_json_success( $post_id ); | |
| } | |
| add_action( 'wp_ajax_cwpai_insert_post', 'cwpai_insert_post' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment