0

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";
}
3
  • 1
    Just curious, why exactly you want them in another table? Does Custom Post Types meet your requirements?
    – Abhik
    May 4 at 3:07
  • @Abhik, I am looking at importing posts and I want to separate them from the regular wp_posts table, so then I can query that table and do ID detections.
    – DevSem
    May 4 at 14:42
  • Sorry for the late reply. In that case, the Custom Post Types fits perfectly. You can separately query for those without having to reinvent the wheel.
    – Abhik
    May 5 at 6:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.