Skip Navigation

[Resolved] Adding a prefix to a auto number field

This thread is resolved. Here is a description of the problem and solution.

Problem:

This customer had created a custom hook to auto assign some numbers to a custom field, however he wanted to prefix the numbers when they are being saved.

Solution:

To add a prefix when manually updating custom field take a look at the example below.

update_post_meta( $post_id, 'wpcf-checklist-task-id', 'SUP'.$last_id );

Notice that i added 'SUP'.$last_id, this will add the text 'SUP' to the id.

This support ticket is created 6 years, 10 months ago. There's a good chance that you are reading advice that it now obsolete.

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
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 14:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Jamaica (GMT-05:00)

This topic contains 1 reply, has 2 voices.

Last updated by Shane 6 years, 10 months ago.

Assisted by: Shane.

Author
Posts
#623422

I am trying to create a ticket number with a prefix of SUP100001 for argementsake and then increments with 1 based on the previous post. i have this code but keeps reverting back to 1

/**************************************************
* Generate a Checklist ID
**************************************************/
function auto_assign_ids( $post_id, $post, $update ) {

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

// get the most recent Project post
$project_args = array(
'numberposts' => 2,
'post_type' => 'checklist',
'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-checklist-task-id', true );

// increment
$last_id++;

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

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

#623459

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Lance,

Thank you for contacting our support forum.

Instead of using the get_post function you can try using this one below.
https://codex.wordpress.org/Function_Reference/wp_get_recent_posts

Also to prefix the value you will do it like this.

update_post_meta( $post_id, 'wpcf-checklist-task-id', 'SUP'.$last_id );

Please let me know if this helps.
Thanks,
Shane