Home › Forums › Backend Issues (wp-admin) › Create Multiple Posts on Back End › Reply To: Create Multiple Posts on Back End
I think I’ve got just about everything down with this. Just one more thing I have to wrestle with (I think, I hope).
The way I have this setup on the backend is that I have a custom post type called “Daily News Briefs”. The author can go in and write whatever they want in the standard WP content editor for that post, and then use the code we’ve been working on to create multiple “sub-posts” with the repeater fields. Those new posts are just saved as standard WP Posts.
In the original code you so kindly fashioned, there is this:
// delete the unused post
wp_delete_post($post_id);
I’ve commented that out because, in my case, I want to keep that post I’ve created in the custom post type.
The only other issue I can find here is that, if I were to go into that custom post type and edit one of the custom fields and re-save, I’ll get a whole other set of duplicate posts created.
What I’ve tried to do is write a conditional that says if the post_id exists, simply update it using wp_update_post, otherwise use wp_insert_post. Unfortunately, that just leads to a duplicate post when trying to update.
Here’s what I’m working with:
// Special ACF Function for Creating Multiple Daily News Brief Posts
function my_acf_save_multiple_posts( $post_id ) {
// get the repeater
$values = get_field('new_daily_brief_posts', $post_id);
// loop through the repeater
foreach( $values as $value ) {
// set the new post arguments
$new_post_article = array(
'post_title' => $value['post_title'],
'post_content' => $value['post_content'],
'post_type' => 'post',
'post_status' => 'publish',
'tags_input' => $value['post_tags']
);
// remove action to avoid infinite loop issue
remove_action('acf/save_post', 'my_acf_save_multiple_posts', 20);
// look to see if this post already exists
$exists = get_post_status ( $ID ) == 'publish';
// if this doesn't exist, create the post.
if( !$exists ){
// post it!
$new_brief_post_id = wp_insert_post($new_post_article);
}
// Update the post if it already exists
else {
// remove action to avoid infinite loop issue
$new_brief_post_id = wp_update_post($new_post_article); }
}
// delete the unused post
//wp_delete_post($post_id);
}
// run after ACF saves the $_POST['acf'] data
add_action('acf/save_post', 'my_acf_save_multiple_posts', 20);
I would imagine that acf/safe_post
would interfere with updating the post?
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.