Skip Navigation

[Closed] Using a php function to fill a custom field if blank

This support ticket is created 3 years, 1 month 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
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 1 reply, has 2 voices.

Last updated by Christian Cox 3 years, 1 month ago.

Assisted by: Christian Cox.

Author
Posts
#1932627

Tell us what you are trying to do?

Basically, I am trying to create a random key as a custom field on a post type called Sessions. This would be a field called Token to eliminate people guessing the ID numbers when using views to show the data.

In PHP, I've been using this function to create the key
$key = implode('-', str_split(substr(strtolower(md5(microtime().rand(1000, 9999))), 0, 24), 6));

I would like to hook into the saving of a new post to check if a key already existing and if now to use that function to create the value.

Is there any documentation that you are following?

Nothing that I found that's like this.

Is there a similar example that we can see?

Nothing that I can think of with code but I think most websites and platforms are capable of producing a unique token to improve security for forgot passwords and similar functions.

What is the link to your site?
hidden link

#1933767

Hello, WordPress offers a hook called save_post that might work for your needs.
https://developer.wordpress.org/reference/hooks/save_post/

add_action( 'save_post', 'tssupp_set_default_unique_key', 10,3 );
 
function tssupp_set_default_unique_key( $post_id, $post, $update ) {
    $post_type_slug = 'posttypeslug';
    $key_field_slug = 'fieldslug';
    
    // Only set for post_type slug = session when custom field value is empty
    if ($post_type_slug !== $post->post_type || get_post_meta( $post_id, 'wpcf-' . $key_field_slug, true ) ) {
        return;
    }
     
    // set default custom field value
    $key = implode('-', str_split(substr(strtolower(md5(microtime().rand(1000, 9999))), 0, 24), 6));
    update_post_meta( $post_id,  'wpcf-' . $key_field_slug, $key);
}

You should replace posttypeslug with the slug of the Sessions post type, and replace fieldslug with the slug of the Types custom field used to store the unique key.

Let me know if this doesn't work as expected and I can take a closer look.

The topic ‘[Closed] Using a php function to fill a custom field if blank’ is closed to new replies.