Latest Post

Hướng Dẫn Cách Sử Dụng Font Chữ Bitmap (.fnt) và Font TrueType (.ttf) trong LibGDX: Tạo và Thêm Font vào Game Java Hướng Dẫn Tạo Và Chỉnh Sửa Giao Diện Game Trong LibGDX: Tạo UI Đẹp Mắt và Hiệu Quả

Trong bài viết này, tôi sẽ hướng dẫn cách tạo một trường tùy chỉnh trong WordPress mà bạn có thể sử dụng để tải lên ảnh bằng một nút upload media.

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');

Chúng ta đã thành công trong việc tạo một phương tiện tùy chỉnh trong WordPress.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *