I used this code which I found on these support forums;
function auto_assign_ids( $post_id, $post, $update ) {
// Only assign ID to new approved promotion posts
if ( $post->post_status == 'publish' && $post->post_type == 'viewed-caravan' ) {
// get the most recent promotion posts
$product_args = array(
'numberposts' => 2,
'post_type' => 'viewed-caravan',
'orderby' => 'post_date',
'order' => 'DESC'
);
$products = get_posts( $product_args );
// get the project_id of the prior post
$last_id = get_post_meta( $products[1]->ID, 'wpcf-product-id', true );
if ( !$last_id ) {
$last_id = 0;
}
// increment
$last_id++;
// set the project_id of the current post
update_post_meta( $post_id, 'wpcf-product-id', $last_id );
}
}
add_action( 'save_post', 'auto_assign_ids', 100, 3 );
It works great, apart from the fact that the ID numbers update to the 'lastest' created ID number when modifying the post.
If you are updating the post I would suggest that you add a conditional in your code to check if field has a value in it before updating the field.
This will help to prevent your posts from getting the latest ID added to their custom field because the check will ensure that only new posts will get the value added.
/**
* Add an auto-incrementing ordernummer field to bpark posts
*/
function auto_assign_bpark_ids( $post_id, $post, $update ) {
if( $update == false ) {
// Only assign ID to new bpark posts
if ( $post->post_type == 'backend-park' ) {
// get the most recent bpark post
$bpark_args = array(
'numberposts' => 1,
'post_type' => 'backend-park',
'orderby' => 'post_date',
'order' => 'DESC'
);
$bparks = get_posts( $bpark_args );
// get the project_id of the prior post
$last_id = isset($bparks[0]) ? get_post_meta( $bparks[0]->ID, 'wpcf-bpark-id', true ) : 0;
// increment
$last_id++;
// set the project_id of the current post
update_post_meta( $post_id, 'wpcf-bpark-id', $last_id );
}
}
}
add_action( 'save_post', 'auto_assign_bpark_ids', 100, 3 );
However, the autonumber still updates on an edit. Which is really frustrating
if(empty(get_post_meta($post_id,'wpcf-bpark-id'))){
// get the most recent bpark post
$bpark_args = array(
'numberposts' => 1,
'post_type' => 'backend-park',
'orderby' => 'post_date',
'order' => 'DESC'
);
$bparks = get_posts( $bpark_args );
// get the project_id of the prior post
$last_id = isset($bparks[0]) ? get_post_meta( $bparks[0]->ID, 'wpcf-bpark-id', true ) : 0;
// increment
$last_id++;
// set the project_id of the current post
update_post_meta( $post_id, 'wpcf-bpark-id', $last_id );
}
This makes it so that the update_post only runs when the post meta is empty. If it already has a value the function will do nothing.