How do I auto increment a custom field when saving a new post?

I’m working with a custom post type called “machine”, that contains a number of Advanced Custom Fields. One of them is SKU, which I would like to automatically be populated whenever a user creates a new post (not when it’s updated).

I’ve created a function that queries the database for the machine CPT with the highest SKU metadata, increases that number by one, and then attempts to write that value to the field in the new post:

function auto_add_sku($new_status, $old_status, $post)
{
if ($post->post_type === ‘machine’) {
$new_sku = 0;

// Get current machine post with highest SKU
$args = [
‘post_type’ => ‘machine’,
‘posts_per_page’ => ‘1’,
‘order’ => ‘DESC’,
‘meta_key’ => ‘sku’,
‘orderby’ => ‘meta_value_num’
];
$sku_query = new WP_Query($args);

if ($sku_query->have_posts()) {
while ($sku_query->have_posts()) {
$sku_query->the_post();
$id = get_the_ID();
$highest_sku = (int) get_field(‘sku’, $id);
$new_sku = $highest_sku + 1;
update_field(‘sku’, $new_sku, $post->ID);
}
}
}
}

add_action(‘transition_post_status’, ‘auto_add_sku’, 10, 3 );

The above retrieves the correct value, but never actually writes it to the database, but I’m not seeing any errors either. What am I doing wrong? Is there a better approach than this?

NB: The SKU doesn’t necessarily have to be an ACF field, but I’d prefer it to be just for consistency.

Read more here:: How do I auto increment a custom field when saving a new post?

Leave a Reply

Your email address will not be published. Required fields are marked *