Auto increment project ID field for every new post


Description: 




Kind:

PHP


PHP:

/**
* Add an auto-incrementing Project ID field to Project posts
*/
function auto_assign_ids( $post_id, $post, $update ) {

// Only assign ID to new project posts
if ( $post->post_status == 'publish' && $post->post_type == 'project' ) {

// get the most recent Project post
$project_args = array(
'numberposts' => 2,
'post_type' => 'project',
'orderby' => 'post_date',
'order' => 'DESC'
);
$projects = get_posts( $project_args );

// get the project_id of the prior post
$last_id = get_post_meta( $projects[1]->ID, 'wpcf-project-id', true );

// increment
$last_id++;

// set the project_id of the current post
update_post_meta( $post_id, 'wpcf-project-id', $last_id );

}
}
add_action( 'save_post', 'auto_assign_ids', 100, 3 );