Add posts to custom table in database instead of wp_posts
What the code does:
- Imports posts, loops through all the posts and calls wp_insert_post to create a new posts for each import.
Objective:
- Import posts and store them in another table, not under the wp_posts table, but retain the associated wp_postmeta tables.
Issues:
For some reason, in it's current state, the new table doesn't get created and the posts don't get inserted - What am I doing wrong? I'd like to import the posts to the new table.
Since I don't have the table created, does $wpdb-insert create the table? If not, do I have to create one beforehand and how so?
Here is the code:
$response = wp_remote_get(
$this-global_endpoint . '/' . $page
);
if (is_wp_error($response)) {
error_log(
print_r(
'Error: module/rest/Endpoint.php, Line 52: ' . $response-get_error_message(),
true
)
);
echo 'Error: ' . $response-get_error_message();
return;
}
try {
$posts = json_decode(
wp_remote_retrieve_body($response),
false,
512,
JSON_THROW_ON_ERROR
);
if (empty($posts)) {
return;
}
} catch (Exception) {
error_log(
print_r('Error: module/rest/Endpoint.php, Line 92: ' . json_last_error(),
true
)
);
return;
}
global $wpdb;
foreach ($posts as $post) {
$my_post = [
'post_type' = 'post',
'post_status' = 'pending',
'post_title' = wp_strip_all_tags($post-title-rendered),
'post_content' = wp_strip_all_tags($post-content-rendered),
'post_excerpt' = wp_strip_all_tags($post-excerpt-rendered),
'post_author' = 0,
'post_date' = $post-date,
'post_date_gmt' = $post-date_gmt,
];
$create_post = wp_insert_post($my_post);
$wpdb-insert('wp_corporate_posts', $my_post);
update_post_meta($create_post, 'corporate_id', $post-id);
echo ID: . $post-id . - Title: . $post-title-rendered . has been imported.\n;
}