Custom Fields
Re-Envisioned
Support General Set default value to field if this value still not exist

This topic contains 3 replies, has 2 voices, and was last updated by  Anh Tran 9 months ago.

  • Creator
    Topic
  • #13036
    Resolved
    Jefferson
    Participant

    Hi!

    I need to set a random hexa code to each post and this code need to persist in database to future search. I have created a custom function to return a code, but now I need to know how to puts this code into de input text field of metabox if this code not exist.

    My function:

    
    function generate_my_own_code( $post_id ){
      
      $post_type = get_post_type($post_id);
      if ( "classified" != $post_type ) return;
    
      $code = rwmb_meta('code', array( 
        'storage_type'    => 'custom_table', 
        'table'           => 'web_classified_meta',
      ));
    
      if( empty($code) ):
        $code = strtoupper(dechex(rand(0x000000, 0xFFFFFF)));
      endif;
    
      return $code;
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Author
    Replies
  • #13053

    Anh Tran
    Keymaster

    Hi Jefferson,

    You can use std attribute for a text field, like this:

    $post_id = isset( $_GET['post'] ) ? intval( $_GET['post'] ) : ( isset( $_POST['post_ID'] ) : intval( $_POST['post_ID'] ) : false );
    $meta_boxes[] = [
        'fields' => [
            [
                'type' => 'text',
                'id' => 'color',
                'std' => generate_my_own_code( $post_id ),
            ],
        ],
    ];
    #13058

    Jefferson
    Participant

    Hi Anh!

    Thank you by support! Works!

    PS1: to old posts the rwmb_meta method prevents adding a default value for the field (but I can run a migration)
    PS2: I will appreciate if “My toppics” in Quick Links of this support system works!

    Regards!

    #13076

    Anh Tran
    Keymaster

    Hi Jefferson,

    Yes, it works only for new posts, since std is used when the meta box has not been saved before. For old posts, obviously meta box is already saved. So you need to do some migration. Perhaps you should share with us here ;). I think many users like that.

    I’ll fix the issue with My topics link now.

Viewing 3 replies - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.