diff --git a/example/oop-example.php b/example/oop-example.php index 2ebe93c..b6915fd 100755 --- a/example/oop-example.php +++ b/example/oop-example.php @@ -127,7 +127,17 @@ function get_settings_fields() { 'type' => 'file', 'default' => '', 'options' => array( - 'button_label' => 'Choose Image' + 'button_label' => __( 'Choose File' ) + ) + ), + array( + 'name' => 'image', + 'label' => __( 'Image', 'wedevs' ), + 'desc' => __( 'Image description', 'wedevs' ), + 'type' => 'image', + 'default' => '', + 'options' => array( + 'button_label' => __( 'Choose Image' ) ) ) ), diff --git a/src/class.settings-api.php b/src/class.settings-api.php index 7cfe4b3..ae5022f 100755 --- a/src/class.settings-api.php +++ b/src/class.settings-api.php @@ -376,6 +376,30 @@ function callback_file( $args ) { echo $html; } + /** + * Displays an image upload field with a preview + * + * @param array $args settings field args + */ + function callback_image( $args ) { + + $value = esc_attr( $this->get_option( $args['id'], $args['section'], $args['std'] ) ); + $size = isset( $args['size'] ) && !is_null( $args['size'] ) ? $args['size'] : 'regular'; + $id = $args['section'] . '[' . $args['id'] . ']'; + $label = isset( $args['options']['button_label'] ) ? + $args['options']['button_label'] : + __( 'Choose Image' ); + $img = wp_get_attachment_image_src( $value ); + $img_url = $img ? $img[0] : ''; + + $html = sprintf( '', $size, $id, $value ); + $html .= '

'; + $html .= ''; + $html .= $this->get_field_description( $args ); + + echo $html; + } + /** * Displays a password field for a settings field * @@ -613,7 +637,6 @@ function(){ $('.wpsa-browse').on('click', function (event) { event.preventDefault(); - var self = $(this); // Create the media frame. @@ -623,15 +646,44 @@ function(){ text: self.data('uploader_button_text'), }, multiple: false - }); + }) - file_frame.on('select', function () { + .on('select', function () { attachment = file_frame.state().get('selection').first().toJSON(); self.prev('.wpsa-url').val(attachment.url).change(); - }); + }) + + // Finally, open the modal + .open(); + }); + + $('.wpsa-image-browse').on('click', function (event) { + event.preventDefault(); + var self = $(this); + + // Create the media frame. + var file_frame = wp.media.frames.file_frame = wp.media({ + title: self.data('uploader_title'), + button: { + text: self.data('uploader_button_text'), + }, + multiple: false, + library: { type: 'image' } + }) + + .on('select', function () { + attachment = file_frame.state().get('selection').first().toJSON(); + var url; + if (attachment.sizes && attachment.sizes.thumbnail) + url = attachment.sizes.thumbnail.url; + else + url = attachment.url; + self.parent().children('.wpsa-image-id').val(attachment.id).change(); + self.parent().children('.wpsa-image-preview').children('img').attr('src', url); + }) // Finally, open the modal - file_frame.open(); + .open(); }); });