Saat mengembangkan theme ataupun plugin WordPress, bisa jadi kamu perlu menggunakan fitur pemilih gambar atau galeri midea WordPress.
Media picker atau pemilih gambar ini sangat bermanfaat, karena sangat memudahkan kita untuk memilih gambar yang sudah ada di website kita begitu juga mengupload gambar baru.
Di bawah ini adalah script contoh cara penggunaannya:
<?php
if( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?>
<form method='post'>
<div class='image-preview-wrapper'>
<img id='image-preview' src='<?php echo wp_get_attachment_url( get_option( 'media_selector_attachment_id' ) ); ?>' style="width: 256px;">
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>">
<input type="hidden" name='image_attachment_id' id='image_attachment_id' value='<?php echo get_option( 'media_selector_attachment_id' ); ?>'>
<input type="submit" name="submit_image_selector" value="Save" class="button-primary">
</form>
<?php
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?>
<script>
jQuery( document ).ready( function( $ ) {
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id;
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>;
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
if ( file_frame ) {
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
file_frame.open();
return;
} else {
wp.media.model.settings.post.id = set_to_post_id;
}
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false
});
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', '128' );
$( '#image_attachment_id' ).val( attachment.id );
wp.media.model.settings.post.id = wp_media_post_id;
});
file_frame.open();
});
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script>