Support

Account

Home Forums General Issues Creating a unique ID in text field only once

Helping

Creating a unique ID in text field only once

  • The code below created a unique id to populate a text field called ‘measurement_id’. This works as expected.

    function yl_create_unique_id_acf_field( $value, $post_id, $field ) {
    	
    		$uniqueid_length	= 8; 
    		$uniqueid			= crypt(uniqid(rand(),1)); 
    		$uniqueid			= strip_tags(stripslashes($uniqueid)); 
    		$uniqueid			= str_replace(".","",$uniqueid); 
    		$uniqueid			= strrev(str_replace("/","",$uniqueid)); 
    		$uniqueid			= substr($uniqueid,0,$uniqueid_length);
    		$uniqueid			= strtoupper($uniqueid);
    
    		$title = 'GM-' . $uniqueid;
    
    		return $title;
    
    }
    add_filter('acf/load_value/name=measurement_id', 'yl_create_unique_id_acf_field', 10, 3);

    The problem:
    After refreshing/updating the field/post, the unique id changes every time but I only want to add the unique id once.

    So only the first time, when the field is still empty and the post hasn’t been created yet, I want to populate the text field with the unique id. After saving/updating the post the unique id needs te stay the same forever.

    So I’m looking for I guess an IF EMPTY statement or something….

  • You can wrap the entire inner function in an if statement to avoid running any code if the field value is not empty.

    
    if ( empty( $value ) ) :
        // contents of {yl_create_unique_id_acf_field} function.
    endif;
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.