Bài viết sau mình sẽ hướng dẫn các bạn tạo 1 custom field trong WordPress có button upload media để upload ảnh:

Bước 1: Đầu tiên chúng ta tạo ra 1 metabox có giao diện như bên trên:
<?php
function vinasupport_custom_meta_boxes( $post_type, $post ) {
add_meta_box(
'vinasupport-meta-box',
__( 'Custom Image' ),
'render_vinasupport_meta_box',
array('post', 'page'), //post types here
'normal',
'high'
);
}
add_action( 'add_meta_boxes', 'vinasupport_custom_meta_boxes', 10, 2 );
function render_vinasupport_meta_box($post) {
$image = get_post_meta($post->ID, 'vinasupport_custom_image', true);
?>
<table>
<tr>
<td><a href="#" class="vinasupport_upload_image_button button button-secondary"><?php _e('Upload Image'); ?></a></td>
<td><input type="text" name="vinasupport_custom_image" id="aw_custom_image" value="<?php echo $image; ?>" /></td>
</tr>
</table>
<?php
}
Bước 2: Nhúng file script vào
<?php
function vinasupport_include_script() {
if ( ! did_action( 'wp_enqueue_media' ) ) {
wp_enqueue_media();
}
wp_enqueue_script( 'vinasupport-script', get_stylesheet_directory_uri() . '/js/vinasupport-script.js', array('jquery'), null, false );
}
add_action( 'admin_enqueue_scripts', 'vinasupport_include_script' );
Bước 3: trong file vinasupport-script.js các bạn thêm phần xử lý handler upload
jQuery(function($){
$('body').on('click', '.vinasupport_upload_image_button', function(e){
e.preventDefault();
let vinasupport_uploader = wp.media({
title: 'Custom image',
button: {
text: 'Use this image'
},
multiple: false
}).on('select', function() {
let attachment = vinasupport_uploader.state().get('selection').first().toJSON();
$('#vinasupport_custom_image').val(attachment.url);
})
.open();
});
});
Bước 4: Lưu thông tin khi submit post
<?php
function vinasupport_save_postdata($post_id)
{
if (array_key_exists('vinasupport_custom_image', $_POST)) {
update_post_meta(
$post_id,
'vinasupport_custom_image',
$_POST['vinasupport_custom_image']
);
}
}
add_action('save_post', 'vinasupport_save_postdata');
Vậy là chúng ta đã tạo thành công 1 custom media trong wordpress.