Home › Forums › General Issues › pre_save_post using \'import_id\'
Hello,
So I have this snippet for the acf/pre_save_form function – however, it seems not to be working properly updating the post before saving it to the database.
function my_pre_save_post( $post_id )
{
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
$title = trim($_POST['acf']['field_5702e3df3ce82']);
// Create a new post
$post = array(
'post_status' => 'draft' ,
'import_id' => $_POST['acf']['field_5702b6a15e788'],
'post_title' => $title,
'post_name' => sanitize_title( $title ),
'post_type' => 'app'
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post', 10, 1);
As you can see, I want to set the ‘import_id’ to an ACF field I have. However, even the post_title is not setting.
Is it because with the ACF Front-End form, I am already setting the ‘new_post’ inside of the array?
acf_form(array(
'post_id' => 'new_post',
'new_post' => array(
'post_type' => 'app'
),
'submit_value' => 'Create'
));
I am using ACF 5+ Pro (5.3.6.1)
Thanks.
The post ID in acf_form()
needs to match the post ID your checking for in your filter
acf_form(array(
'post_id' => 'new',
'new_post' => array(
'post_type' => 'app'
),
'submit_value' => 'Create'
));
You can use it for multiple post types by varying this ID for example new_page
, new_product
, new_whatever_you_want
.
If you use new_post
in when you call acf_form()
ACF will automatically create a new “Post” post and your filter will do nothing.
This is the code that works for me. Note the $GLOBALS['acf_form']['return']
function my_pre_save_post( $post_id )
{
// check if this is to be a new post
if( $post_id != 'new' ) {
return $post_id;
};
$title = trim($_POST['acf']['field_5702e3df3ce82']);
// Create a new post
$post = array(
'post_status' => 'publish' ,
'import_id' => $_POST['acf']['field_5702b6a15e788'],
'post_title' => $title,
'post_name' => sanitize_title( $title ),
'post_type' => 'app'
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $GLOBALS['acf_form']['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post');
The topic ‘pre_save_post using \'import_id\'’ is closed to new replies.
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.