Skip to content

Commit 47781d7

Browse files
committed
Add image field type
Works the same as file field type but with a preview of the image. Signed-off-by: Roi Dayan <[email protected]>
1 parent e5ed957 commit 47781d7

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

example/oop-example.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ function get_settings_fields() {
129129
'name' => 'file',
130130
'label' => __( 'File', 'wedevs' ),
131131
'desc' => __( 'File description', 'wedevs' ),
132-
'type' => 'file',
132+
'type' => 'image',
133133
'default' => '',
134134
'options' => array(
135135
'button_label' => 'Choose Image'

src/class.settings-api.php

+28-1
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,28 @@ function callback_file( $args ) {
358358
echo $html;
359359
}
360360

361+
/**
362+
* Displays an image upload field with a preview
363+
*
364+
* @param array $args settings field args
365+
*/
366+
function callback_image( $args ) {
367+
368+
$value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) );
369+
$size = isset( $args['size'] ) && !is_null( $args['size'] ) ? $args['size'] : 'regular';
370+
$id = $args['section'] . '[' . $args['id'] . ']';
371+
$label = isset( $args['options']['button_label'] ) ?
372+
$args['options']['button_label'] :
373+
__( 'Choose Image' );
374+
375+
$html = sprintf( '<input type="text" class="%1$s-text wpsa-url" id="%2$s[%3$s]" name="%2$s[%3$s]" value="%4$s"/>', $size, $args['section'], $args['id'], $value );
376+
$html .= '<input type="button" class="button wpsa-browse" value="' . $label . '" />';
377+
$html .= $this->get_field_description( $args );
378+
$html .= '<p class="wpsa-image-preview"><img src=""/></p>';
379+
380+
echo $html;
381+
}
382+
361383
/**
362384
* Displays a password field for a settings field
363385
*
@@ -567,12 +589,17 @@ function(){
567589
file_frame.on('select', function () {
568590
attachment = file_frame.state().get('selection').first().toJSON();
569591

570-
self.prev('.wpsa-url').val(attachment.url);
592+
self.prev('.wpsa-url').val(attachment.url).change();
571593
});
572594

573595
// Finally, open the modal
574596
file_frame.open();
575597
});
598+
599+
$('input.wpsa-url').on( 'change keyup paste input', (function() {
600+
var self = $(this);
601+
self.next().parent().children( '.wpsa-image-preview' ).children( 'img' ).attr( 'src', self.val() );
602+
})).change();
576603
});
577604
</script>
578605

0 commit comments

Comments
 (0)