Cómo agregar un meta box para subir imágenes usando el cargador de medios de WordPress

11 feb 2017, 06:34:22
Vistas: 18K
Votos: 1

No quiero que aparezca este popup thickbox al subir el archivo de imagen mediante el metabox. Quiero agregar el popup del cargador de medios de WordPress al subir archivos usando el metabox. ¿Alguna idea?http://wordpress.stackexchange.com/questions/67065/add-upload-media-button-in-meta-box-field

0
Todas las respuestas a la pregunta 1
3

Encontré la mejor solución, por favor revísala:

Código jQuery

jQuery(function($){
    /*
     * Evento para seleccionar/subir imagen(es)
     */
    $('body').on('click', '.misha_upload_image_button', function(e){
        e.preventDefault();
 
            var button = $(this),
                custom_uploader = wp.media({
            title: 'Insertar imagen',
            library : {
                // descomenta la siguiente línea si quieres adjuntar la imagen al post actual
                // uploadedTo : wp.media.view.settings.post.id, 
                type : 'image'
            },
            button: {
                text: 'Usar esta imagen' // texto del botón
            },
            multiple: false // para selección múltiple de imágenes cambia a true
        }).on('select', function() { // también tiene eventos "open" y "close"
            var attachment = custom_uploader.state().get('selection').first().toJSON();
            $(button).removeClass('button').html('<img class="true_pre_image" src="' + attachment.url + '" style="max-width:95%;display:block;" />').next().val(attachment.id).next().show();
            /* si configuras multiple a true, aquí hay código para obtener los IDs de las imágenes
            var attachments = frame.state().get('selection'),
                attachment_ids = new Array(),
                i = 0;
            attachments.each(function(attachment) {
                attachment_ids[i] = attachment['id'];
                console.log( attachment );
                i++;
            });
            */
        })
        .open();
    });
 
    /*
     * Evento para eliminar imagen
     */
    $('body').on('click', '.misha_remove_image_button', function(){
        $(this).hide().prev().val('').prev().addClass('button').html('Subir imagen');
        return false;
    });
 
});

Functions.php

function misha_include_myuploadscript() {
    /*
     * Recomiendo añadir condiciones adicionales para no cargar los scripts en cada página
     * como:
     * if ( !in_array('post-new.php','post.php') ) return;
     */
    if ( ! did_action( 'wp_enqueue_media' ) ) {
        wp_enqueue_media();
    }
 
    wp_enqueue_script( 'myuploadscript', get_stylesheet_directory_uri() . '/customscript.js', array('jquery'), null, false );
}
 
add_action( 'admin_enqueue_scripts', 'misha_include_myuploadscript' );

function misha_image_uploader_field( $name, $value = '') {
    $image = ' button">Subir imagen';
    $image_size = 'full'; // sería mejor usar tamaño thumbnail aquí (150x150 o similar)
    $display = 'none'; // estado de visualización del botón "Eliminar imagen"
 
    if( $image_attributes = wp_get_attachment_image_src( $value, $image_size ) ) {
 
        // $image_attributes[0] - URL de la imagen
        // $image_attributes[1] - ancho de la imagen
        // $image_attributes[2] - altura de la imagen
 
        $image = '"><img src="' . $image_attributes[0] . '" style="max-width:95%;display:block;" />';
        $display = 'inline-block';
 
    } 
 
    return '
    <div>
        <a href="#" class="misha_upload_image_button' . $image . '</a>
        <input type="hidden" name="' . $name . '" id="' . $name . '" value="' . $value . '" />
        <a href="#" class="misha_remove_image_button" style="display:inline-block;display:' . $display . '">Eliminar imagen</a>
    </div>';
}

/*
 * Añadir un meta box
 */
add_action( 'add_meta_boxes', 'misha_meta_box_add' );
 
function misha_meta_box_add() {
    add_meta_box('mishadiv', // ID del meta box
        'Más configuraciones', // título del meta box
        'misha_print_box', // función callback que imprime el HTML del meta box
        'post', // tipo de post donde añadirlo
        'normal', // prioridad
        'high' ); // posición
}
 
/*
 * HTML del Meta Box
 */
function misha_print_box( $post ) {
    $meta_key = 'second_featured_img';
    echo misha_image_uploader_field( $meta_key, get_post_meta($post->ID, $meta_key, true) );
}
 
/*
 * Guardar datos del Meta Box
 */
add_action('save_post', 'misha_save');
 
function misha_save( $post_id ) {
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
        return $post_id;
 
    $meta_key = 'second_featured_img';
 
    update_post_meta( $post_id, $meta_key, $_POST[$meta_key] );
 
    // si deseas adjuntar la imagen subida a este post, descomenta la línea:
    // wp_update_post( array( 'ID' => $_POST[$meta_key], 'post_parent' => $post_id ) );
 
    return $post_id;
}
4 jul 2017 15:11:46
Comentarios

¿cómo mostrar o imprimir la imagen almacenada a través de este método?

J. Shabu J. Shabu
28 jun 2018 20:26:18

excelente hook @Ravi pero tengo la misma pregunta que Shabu, ¿cómo usar la imagen subida?? gracias de antemano

Said Erraoudy Said Erraoudy
2 abr 2021 19:52:20

el campo uploader aquí está almacenando un ID de adjunto en second_featured_img, usarías get_post_meta para recuperar ese ID y luego usarlo para obtener una URL de imagen para el tamaño que desees de la misma manera que con cualquier otro adjunto

Tom J Nowell Tom J Nowell
9 feb 2025 19:47:02