Home › Forums › General Issues › Auto generate post_title with acf_form
Hi acf-community!
I use acf_form to create posts the custom post type “tickets” from the wordpress frontend:
<?php
acf_form(array(
'post_id' => 'new_post',
'post_title' => false,
'post_content' => false,
'new_post' => array(
'post_type' => 'tickets',
'post_status' => 'publish'
),
fields' => array('field_5ba8b0c6a5116', 'field_5ba8b08c96be1'),
);
?>
I use the following filter to create a custom post title. This is working perfectly when i create a post of the cpt “tickets” in the backend but its not working when the post is created from the frontend with acf_form:
add_filter('title_save_pre','auto_generate_post_title');
function auto_generate_post_title($title) {
global $post;
if (isset($post->ID)) {
if (empty($_POST['post_title']) && 'tickets' == get_post_type($post->ID)) {
// get the current post ID number
$id = get_the_ID();
// add ID number with order strong
$title = 'ticket-'.$id;
}
}
return $title;
}
What am i doing wrong?
I’m not sure of all of the details of the title_save_pre
hook. If it is firing for acf_form()
saves then most likely the global $post
has no value. You will also not have a way to get the post or post ID in this function since the value of the $_POST
post ID will likely be new_post
.
It is always best to use the acf/save_post
hook when dealing with ACF, front end or back https://www.advancedcustomfields.com/resources/acf-save_post/
You could also create your own acf/pre_save_post
for the front end https://www.advancedcustomfields.com/resources/acf-pre_save_post/
Pretty sure you can add the title to the new post like so:
<?php
acf_form(array(
'post_id' => 'new_post',
'post_title' => false,
'post_content' => false,
'new_post' => array(
'post_type' => 'tickets',
'post_status' => 'publish',
'post_title' => 'my title'
),
fields' => array('field_5ba8b0c6a5116', 'field_5ba8b08c96be1'),
);
?>
Seems nicer, but you don’t have access to the new post ID 🙁
You must be logged in to reply to this topic.
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!
2022 was a big year for Advanced Custom Fields, with more capabilities, a new generation of ACF Blocks, a refreshed UI, and a new home. Our year in review post looks at advancements we’ve made and offers a glimpse of the future.
— Advanced Custom Fields (@wp_acf) January 6, 2023
https://t.co/HahJUCcyH4
© 2023 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.