Home › Forums › ACF PRO › Pre-populated incremented reference number field › Reply To: Pre-populated incremented reference number field
What you need to do is create an WP option that holds the value last used.
// on WP init create an option value if it does not exist
// this code can be deleted after the option is created
// or it can be left alone
add_action('init', 'create_my_reference_options');
function create_my_reference_options() {
$reference = get_option('reference_field_counter', false);
if (!$reference) {
update_options('reference_field_counter', 12345);
}
}
Having a counter in place you can then use an acf/prepare_field filter to set the value if it is not set
add_filter('acf/prepare_field/name=reference_field_name', 'set_reference_value');
function set_reference_value($field) {
if (empty($field('value'])) {
$reference = intval(get_option('reference_field_counter'));
$reference++;
$field['value'] = $refefence;
update_options('reference_field_counter', $reference);
}
return $field;
}
Note that this will continue to increment the reference number each time the page is loaded even if the post is not saved and may leave gaps in your numbering system. If this in not the case then it gets more complicated. Rather than using an option you would instead need to do a query in the prepare_field filter to get the post with the highest number and then you that value to set the new one. But this also has drawbacks. In the instance where multiple posts are created at the same time then it is likely that numbers will be repeated. I doubt there is a full-proof method.
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.