Custom Fields
Re-Envisioned
Support General Custom Field Type Issues

  • Creator
    Topic
  • #29770
    Resolved Nicholas Cox
    Participant

    Hi

    I am building my first custom field type and its not so easy as I first thought. I cant seem to find much information on this subject in the forum, fb etc.

    I am basically building a input field file which allows the user to upload a single or multiple images using FileReader (Web API) and output them as base64 so I can pass the data on .

    This is a general demo I found which I am basing my code off https://bootsnipp.com/snippets/2eNKz. The demo allows you to upload images and reorder them, but generates a base64 preview of the image locally within the browser.

    Example of where I am at is below, any help would be great.

    1. Am I correctly enqueued JS file? I need this for the FileReader script. Or will it be easier to put this into a template? or within the class?
    2. I have included the input field but I can't work out how to pass the base64 stings over to $meta after the images have been encoded and exist in the DOM? do I have to call it via JS? or include an array somewhere so Metabox can use it automatically?
    if ( class_exists( 'RWMB_Field' ) ) {
        
        class RWMB_ImagePreview_Field extends RWMB_Field {
                
            public static function admin_enqueue_scripts() {
                wp_enqueue_script( 'dc-file', dirname( __FILE__ ) . '/test.js', array(), '', true );
            }
            
            public static function html( $meta, $field ) {
    
                return sprintf(
                    
                    $html = '<div class="container"><div class="form-group"><div class="upload-count"></div>
                            <button type="button" class="rwmb-browse-button browser button button-hero" href="javascript:void(0)" onclick="$("#pro-image").click()">Select Files</button>
                            <input type="file" id="%s" name="pro-image" style="display: none;" class="form-control" multiple></div><div class="preview-images-zone"></div></div>',
                    $field['field_name'],
                    $field['id'],
                    $meta
                );
            }
    
            public static function normalize( $field ) {
                
                $field = wp_parse_args( $field, array(
                    'sanitize_callback' => [ __CLASS__, 'custom_sanitize' ],
                ) );
                $field = parent::normalize( $field );
                return $field;
            }
    
            public static function custom_sanitize( $value, $field, $old_value, $object_id ) {
                
                // Do something with $value.
            }
        }
    }
Viewing 9 replies - 1 through 9 (of 9 total)
Viewing 9 replies - 1 through 9 (of 9 total)
  • You must be logged in to reply to this topic.