0

I have a custom post type called 'Customers'. Data is taken using a front end form, which is then saved into the post type. But I want the titles to be automatically generated as unique incremental numbers. Meaning, it will go as 1,2,3,4..

I got most of this figured out, except a small issue. If there are no posts, then the new title will be 1. If there are posts, then code will fetch the most recent one, check it's title and generate new title by increasing it by 1. So far so good.

But if I delete the most recent post, new post added after that will be assigned same title # as the last one. Also, if I delete all posts, titles will start again from #1. I don't want any of the titles to repeat, no matter if any or even all of previous posts are deleted. I want them to always be go on incrementing, never assign the same # again.

1

The method for increment you used will not achieve what you want to if you delete the posts. Instead you can save the counter in wp_options table on front-end form submission, something like:

if(get_option('customers_count')){
    $count = get_option('customers_count', true);
    update_option('customers_count', $count+1);
} else {
    /** This will automatically add the option if it does not exist. **/
    update_option('customers_count', 1); // adding first time as value 1        
}

It will always take new number as post title #.

Note: Make sure you update option only when submit form for adding a new post and not for edit post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.