0

I am trying to do something similar to this block of code - but with tax terms within a taxonomy rather than custom fields in a post

In short, I want to auto increment a simple number value in a taxonomy term for a custom taxonomy when the term is saved so that, each time a new term is created in the cms, it is auto assigned the next number higher from the previous term - so I would end with a list of tax terms like this

taxonomy: job number terms: 1, 2, 3, 4, 5, 6 and so on

Thanks

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

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

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

    // get the project_id of the prior post
    //get the custom field value of a post
    $last_id = get_post_meta( $projects[1]->ID, 'job_number', true );

    // increment
    $last_id++;

    // set the project_id of the current post
    update_post_meta( $post_id, 'job_number', $last_id );
    }
 }
add_action( 'save_post', 'auto_assign_ids', 100, 3 );
1
/**
* Add an auto-incrementing Project ID field to Design feedback posts
*/
function auto_assign_ids( $post_id, $post, $update ) {

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

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

    // get the project_id of the prior post
    //get the custom field value of a post
    $last_id = get_post_meta( $projects[1]->ID, 'job_number', true );

    // increment
    $last_id++;

     // set the project_id of the current post
     if ( !add_post_meta( $post_id, 'job_number', $last_id, true ) ) { 

     update_post_meta( $post_id, 'job_number', $last_id );

     }

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

I'm not 100% sure but I think the issue is that the page doesn't have an ID yet so you can't update it, you have to insert it first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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