I want to have a numerical counter for a CPT in a custom field a bit like a post ID but only for that custom post type, starting from 1. I've tried to start by setting a custom field value from an incrementing value in options when a post is first created.

I'm trying to call this and increment on new post save but it keeps over-writing it when post is saved/updated, etc so I'm using the wrong hook but can't seem to find the right one.

// Maintain Asset register count in Options Table and assign to new assets
function define_asset( $post_id, $post ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( ! current_user_can( 'edit_post', $post_id ) ) return;
    global $wpdb;
    $isAsset = get_post_meta($post_id, 'assetID', false);
    if ($isAsset ) {
        $count = get_option('assetID', true);
        update_option('assetID', $count+1);
        $assetID = get_option('assetId');
        str_pad($assetID, 5, '0', STR_PAD_LEFT);
        } else {
        /** This will automatically add the option if it does not exist. **/
        update_option('assetID', 1); // adding first time as value 1
        $assetID = str_pad($assetID, 5, '0', STR_PAD_LEFT);
        update_post_meta( $post_id, 'assetID', $assetID );
//add_action( 'post_updated',  'define_asset', 20, 2 ); 
add_action( 'save_post', 'define_asset', 20, 2 ); // This works but increments on each save
//add_action( 'publish_post', 'define_asset', 20, 2 ); // This works but increments on each save
//add_action( 'publish_inventory',  'define_asset', 20, 2 ); // 
//add_action( 'draft_to_published',  'define_asset', 20, 2 ); // This doesn't work

1 Answer 1


The save_post hook has a third parameter named $update, so you can use it to check if the post is being created and not updated.

function define_asset( $post_id, $post, $update ) {
    if ( $update ) {

    // else, run your code...
add_action( 'save_post', 'define_asset', 20, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.