Problem: I would like to automatically increment a custom field value when I create a new post in my custom post type. The field value should be the highest field value from the other posts, plus one.
Solution:
Add this code to functions.php:
/** * Add an auto-incrementing ordernummer field to telorder posts */ function auto_assign_ids( $post_id, $post, $update ) { if( $update == false ) { // Only assign ID to new telorder posts if ( $post->post_type == 'telorder' ) { // get the most recent telorder post $telorder_args = array( 'numberposts' => 1, 'post_type' => 'telorder', 'orderby' => 'post_date', 'order' => 'DESC' ); $telorders = get_posts( $telorder_args ); // get the project_id of the prior post $last_id = isset($telorders[0]) ? get_post_meta( $telorders[0]->ID, 'wpcf-ordernummer', true ) : 0; // increment $last_id++; // set the project_id of the current post update_post_meta( $post_id, 'wpcf-ordernummer', $last_id ); } } } add_action( 'save_post', 'auto_assign_ids', 100, 3 );
Relevant Documentation:
https://codex.wordpress.org/Template_Tags/get_posts
https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
https://codex.wordpress.org/Function_Reference/update_post_meta
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 5 replies, has 3 voices.
Last updated by 6 years, 7 months ago.
Assisted by: Christian Cox.