Thanks to @TomJNowell’s hint I managed to get it working with a simple check if the post already exists (using the post_exists
function). This code is included in the functions.php
file.
Additionally, the loop only runs if called from the backend using the is_admin
function.
Here’s the working example:
function ekesto_insert_post(){
// config
$post_type="event";
// post_exists() is by default only available in the admin, so let's get it in case the page is loaded on the frontend
require_once(ABSPATH . 'wp-admin/includes/post.php');
$import_array = array();
$new_post = array(
'post_title' => 'Test Event',
'post_status' => 'publish',
'post_type' => $post_type
);
$new_post_custom_fields = array(
'category' => 29,
'date_start' => '20231101',
'venue_name' => 'Schloss Glarisegg',
'location' => 'Steckborn (ZH)',
'organizer_name' => 'Pathways Courses',
'organizer_url' => 'https://pathways-courses.org/'
);
$import_array[] = array($new_post, $new_post_custom_fields);
// only run code in the backend
if( is_admin()) {
foreach ($import_array as $array) {
// check if post title exists
$fount_post = post_exists( $array[0]['post_title'],'','',$post_type,'publish');
// 0 is returned if post doesn't exist yet
if ($fount_post === 0) {
// Insert post into the database
$post_id = wp_insert_post($array[0], true); // Use $wp_error set to true for error handling
// Fill Advanced Custom Fields (ACF) fields
foreach ($array[1] as $key => $value) {
update_field($key, $value, $post_id);
}
// Check if there was an error during post insertion
if (is_wp_error($post_id)) {
// Error occurred while inserting the post
echo "Error: " . $post_id->get_error_message();
} else {
// The post was successfully inserted, and $post_id contains the post ID
echo "Post inserted successfully. New Post ID: " . $post_id;
}
}
}
}
}
add_action('after_setup_theme', 'ekesto_insert_post');
Note: The code also adds Advanced Custom Fields (ACF) data using the ACF function update_field()
.