Set default value to field if this value still not exist

Support General Set default value to field if this value still not existResolved

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #13036
    JeffersonJefferson
    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;
    }
    #13053
    Anh TranAnh 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
    JeffersonJefferson
    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 TranAnh 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 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.