'WordPress: Import posts into new database table similar to wp_posts()

So what I am trying to do is import posts from another website using a specific endpoint (DONE) and then import them into a new database table, but have it adjusted similar to how the wp_posts() table looks, so I can have these imported posts be separated from the wp_posts() since I won't be using them.

Issues:

  • How do I properly build a table with columns for the $posts that need to be imported, all of the keys are under $my_post.
  • If I call wp_insert_post() would that insert the post under the wp_posts() table or can I pick which table? I want a new table called wp_corporate_posts().
  • The goal of this is to create columns based on the $my_post keys and then import them into a wp_corporate_posts() table.

Here is what I code that I have done:

global $wpdb;
$wpdb->hide_errors();
if (!function_exists('dbDelta')) {
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
$collate = '';
if ($wpdb->has_cap( 'collation')) {
    $collate = $wpdb->get_charset_collate();
}
$table_name = 'corporate_posts';
maybe_create_table(
    $wpdb->prefix . $table_name,
    "CREATE TABLE " . $table_name . " (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    
    PRIMARY KEY (id)
    ) $collate;"
);
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($table_name, $my_post);
    update_post_meta($create_post, 'corporate_id', $post->id);
    echo "ID: " . $post->id . " - Title: " . $post->title->rendered . " has been imported.\n";
}

All help will be appreciated!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source