Custom field default value with counter

I have a custom post type called machine and a custom field ‘reference_number’ what I want is to add a default value to the custom field when creating a new machine and show this value before the save.

Here is what I came up with so far.

Read More
function set_default_meta($post_ID){
    $current_field_value = get_post_meta($post_ID,'reference_number',true);

    // this needs to be like, machine 1, machine 2, ..
    $default_meta = 'machine '; 
    if ($current_field_value == '' && !wp_is_post_revision($post_ID)){
            add_post_meta($post_ID,'reference_number',$default_meta,true);
    }
    return $post_ID;
}

add_action('wp_insert_post','set_default_meta');

The code works and add ‘machine ‘ value to the custom field, but only after saving the post. how can I show it when just starting to add the post. and How can I add a counter variable that increase by one in every new post.

Thanks

EDIT

Thanks so much to @s_ha_dum for code, I also asked a question at Pods forum and they helped a lot with the global variable. So the final code is to

1- add global variable as default in pods admin

 {@globals.reference_number} 

2- add this code in functions.php

// Set reference number to be dynamicaly increased every time machine created.
function get_next_reference_number() {
    global $wpdb;
    $ref = $wpdb->get_var("SELECT max(cast(meta_value as unsigned)) FROM wp_postmeta WHERE meta_key='reference_number'");
    $GLOBALS[ 'reference_number' ] = (!empty($ref)) ? $ref + 1 : 1;
}

add_action('wp_insert_post','get_next_reference_number');

And it works.

Related posts

1 comment

  1. I don’t know how the pods framework works so I can’t tell you how to set the value but I can get you started.

    First, don’t store your entire “machine %n” string. The “machine” part it going to be the same for all entries, correct? Then just save the “%n“.

    Now, when you need to add a new post …

    function get_next_reference_number() {
      global $wpdb;
      $ref = $wpdb->get_var("SELECT MAX(meta_value) FROM {$wpdb->postmeta} WHERE meta_key = 'reference_number'");
      return (!empty($ref)) ? $ref + 1 : 1;
    }
    

    Hopefully you can work that into your Pods code.

Comments are closed.