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.

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)){
    return $post_ID;


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 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


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;


And it works.

  • How do you show the field? In a metabox? Or are you using the Custom Fields default box?
    – fuxia
    Jun 3, 2013 at 5:21
  • I use podsframework.org for creating custom fields. it has a default field option but with no option for add a counter so may be I can make it outside the plugin if this possible.
    – Ahmad Ajmi
    Jun 3, 2013 at 5:49

1 Answer 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.

  • Thanks so much, it works with as you said. I updated my question with the full code.
    – Ahmad Ajmi
    Jun 14, 2013 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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