Let's say I have a custom post type "Clients"
And one of the custom fields of the post type is "Contact ID Number".
As we add new Client records we would like to assign a new unique "Contact ID Number" to each one.
The numbers should be sequential.
And we would like WordPress to automatically assign the "Contact ID Number" when the new Client record is saved.
There wouldn't be a huge number of Client records.
Less than 100 I imagine.
So one way I guess that this could be accomplished is to add a custom code snippet such that:
- When a Client record is saved, the system loops through all the existing Client records, finds the one with the highest value, increments that value by "1", and saves that value into the custom field of the new record.
Any suggestions on how to make that work with ToolSet?
thanks.
Hello,
There isn't such kind of built-in feature within Toolset plugins, so you will need to consider custom codes.
For example, after user save a "Clients" post, use WP action hook "save_post" to trigger a PHP function:
https://developer.wordpress.org/reference/hooks/save_post/
In this PHP function, setup the "Contact ID Number" value as what you want:
https://developer.wordpress.org/reference/functions/update_post_meta/
One issue needs to pay attention:
If the "Contact ID Number" custom field is created with Toolset Types plugin, Types plugin will prepend slug "wpcf-" before the field slug, so you need to add "wpcf-" into the custom field meta_key, for example: wpcf-contact-id-number
Thank you for that reply.
Yes, I was aware of those things.
My question was really "how can i write a function that loops through all the records of a custom post type AND accesses the value of a custom field in order to determine what the highest value is."
As I mentioned above, you will need consider custom codes, for example:
Get highest "Contact ID Number" value from "Clients" posts
https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
‘meta_value_num‘ – Order by numeric meta value
https://developer.wordpress.org/reference/classes/wp_query/#pagination-parameters
posts_per_page here you can use value 1
Can you give me a hint on how to loop through all the records of a post type?
Thanks. I will do further research on my own.