Shaine Eugene Mednikov
Shaine Eugene Mednikov

Reputation: 395

How to create db counter in wordpress

Let's say I've got custom post type Order and custom field Order Number, and let's say these custom posts are created on a form submission.

What I need is to increment this Order Number field automatically in the safe way, so that numbers aren't duplicated.

The trivial solution: on form submission, find last order and use its number + 1. But in this case when 2 users submit form at the same time, they will get the same order number.

I was doing such things with custom frameworks in the past: lock the db row for update, increment the number, then release. This will safely increment the number. But this will require creating separate table just for this counter and I'd prefer to avoid that.

I didn't find something ready in the WP API.

I'm using WP 3.8 over MySQL.

Upvotes: 0

Views: 357

Answers (1)

Bud Damyanov
Bud Damyanov

Reputation: 31839

Auto-increment functionality is implemented a long time ago in MySQL, what you have to do is just specify the ID of your table to be AUTO_INCREMENT.

However, if you insert your data on form submission and you create a custom post type, then you are inserting the data in wp_posts table, but this is already done there, because this is the table, where all posts are stored in Wordpress and it already have ID set to AUTO_INCREMENT.

Upvotes: 1

Related Questions