Creare un Uploader di Immagini per Widget

21 dic 2013, 23:51:18
Visualizzazioni: 23.8K
Voti: 3

Ho trovato questo post//

Utilizzare Media upload nel widget personalizzato su WordPress 3.5

Non ho esperienza in nulla di questo quindi ho più o meno copiato il codice che ha fornito nel mio file functions.php. Ho caricato il JS e tutto il resto...

Ho poi sostituito del codice che "sven" ha pubblicato nella sua risposta.

L'uploader funziona perfettamente ma quando visualizzo il frontend l'immagine non viene nemmeno mostrata...

Ecco il codice nel mio functions.php//

(include le sidebar registrate e il widget personalizzato ecc)

if (function_exists('register_sidebar')) {
 register_sidebar(array(
  'name' => 'Sidebar Sinistra',
  'id'   => 'left-sidebar', 
  'description'   => 'Area Widget',
  'before_widget' => '<div id="one" class="two"><h1>EOTW//</h1>',
  'after_widget'  => '</div>',
  'before_title'  => '<h2>',
  'after_title'   => '</h2>'
 ));
}

add_action('widgets_init', 'ctUp_ads_widget');
function ctUp_ads_widget() {
register_widget( 'ctUp_ads' );
}

function ctUp_wdScript(){
wp_enqueue_media();
wp_enqueue_script('adsScript', get_template_directory_uri() . '/js/ads.js');
}
add_action('admin_enqueue_scripts', 'ctUp_wdScript');

class ctUp_ads extends WP_Widget{

function ctUp_ads() {
    $widget_ops = array( 'classname' => 'ctUp-ads' );
    $control_ops = array( 'width' => 250, 'height' => 350, 'id_base' => 'ctUp-ads-widget' );
    $this->WP_Widget( 'ctUp-ads-widget','EOTW', $widget_ops, $control_ops );
}

public function widget($args, $instance){ 
    extract( $args );   
?>
<a href="#"><img src="<?php echo esc_url($instance['image_uri']); ?>" /></a>
<?php }

function update($new_instance, $old_instance) {
    $instance = $old_instance;
    $instance['text'] = strip_tags( $new_instance['text'] );
    $instance['image_uri'] = strip_tags( $new_instance['image_uri'] );
    return $instance;
}

public function form($instance){ ?>
<p>
  <label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Testo', 'themename'); ?></label><br />
  <input type="text" name="<?php echo $this->get_field_name('text'); ?>" id="<?php echo $this->get_field_id('text'); ?>" value="<?php echo $instance['text']; ?>" class="widefat" />
</p>
<p>
  <label for="<?php echo $this->get_field_id('image_uri'); ?>">Immagine</label><br />
    <img class="custom_media_image" src="<?php if(!empty($instance['image_uri'])){echo $instance['image_uri'];} ?>" style="margin:0;padding:0;max-width:100px;float:left;display:inline-block" />
    <input type="text" class="widefat custom_media_url" name="<?php echo $this->get_field_name('image_uri'); ?>" id="<?php echo $this->get_field_id('image_uri'); ?>" value="<?php echo $instance['image_uri']; ?>">
    <input type="button" value="<?php _e( 'Carica Immagine', 'themename' ); ?>" class="button custom_media_upload" id="custom_image_uploader"/>
</p>
<?php } }  ?>

Ecco il JS//

jQuery(document).ready( function(){
function media_upload( button_class) {
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
jQuery('body').on('click',button_class, function(e) {
    var button_id ='#'+jQuery(this).attr('id');
    /* console.log(button_id); */
    var self = jQuery(button_id);
    var send_attachment_bkp = wp.media.editor.send.attachment;
    var button = jQuery(button_id);
    var id = button.attr('id').replace('_button', '');
    _custom_media = true;
    wp.media.editor.send.attachment = function(props, attachment){
        if ( _custom_media  ) {
           jQuery('.custom_media_id').val(attachment.id); 
           jQuery('.custom_media_url').val(attachment.url);
               jQuery('.custom_media_image').attr('src',attachment.url).css('display','block');   
        } else {
            return _orig_send_attachment.apply( button_id, [props, attachment] );
        }
    }
    wp.media.editor.open(button);
    return false;
});
}
media_upload( '.custom_media_upload');
});

Ora la mia domanda è, cosa devo esattamente correggere per far funzionare questo uploader di immagini? Ho pensato che gli aggiornamenti forniti da "sven" avrebbero aiutato ma chiaramente mi sta sfuggendo qualcosa. Per favore aiutate.

1
Commenti

@Sven Potrebbe esserci un altro modo per incorporare un caricatore di immagini per i widget in 3.8?

keilowe keilowe
22 dic 2013 03:13:50
Tutte le risposte alla domanda 2
3
10

Affrontiamolo nel dettaglio: La sidebar registrata (con l'ID left-sidebar) ha due argomenti per racchiudere l'intero widget (before_widget e after_widget) che puoi visualizzare tramite echo $before_widget e echo $after_widget nel tuo widget (vedi la mia versione qui sotto):

<?php

// Registra la sidebar
if (function_exists('register_sidebar')) {
    register_sidebar(
        array(
        'name' => 'Sidebar Sinistra',
        'id' => 'left-sidebar',
        'description' => 'Area Widget',
        'before_widget' => '<div id="one" class="two">',
        'after_widget' => '</div>',
        )
    );
}

// Registra il widget
add_action('widgets_init', 'ctUp_ads_widget');
function ctUp_ads_widget() {
    register_widget( 'ctUp_ads' );
}

// Carica script aggiuntivi per l'amministrazione
add_action('admin_enqueue_scripts', 'ctup_wdscript');
function ctup_wdscript() {
    wp_enqueue_media();
    wp_enqueue_script('ads_script', get_template_directory_uri() . '/js/widget.js', false, '1.0.0', true);
}

// Widget
class ctUp_ads extends WP_Widget {

    function ctUp_ads() {
        $widget_ops = array('classname' => 'ctUp-ads');
        $this->WP_Widget('ctUp-ads-widget', 'EOTW', $widget_ops);
    }

    function widget($args, $instance) {
        echo $before_widget;
?>

    <h1><?php echo apply_filters('widget_title', $instance['text'] ); ?></h1>
    <img src="<?php echo esc_url($instance['image_uri']); ?>" />

<?php
        echo $after_widget;

    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['text'] = strip_tags( $new_instance['text'] );
        $instance['image_uri'] = strip_tags( $new_instance['image_uri'] );
        return $instance;
    }

    function form($instance) {
?>

    <p>
        <label for="<?php echo $this->get_field_id('text'); ?>">Testo</label><br />
        <input type="text" name="<?php echo $this->get_field_name('text'); ?>" id="<?php echo $this->get_field_id('text'); ?>" value="<?php echo $instance['text'] ?? ''; ?>" class="widefat" />
    </p>
    <p>
        <label for="<?= $this->get_field_id( 'image_uri' ); ?>">Immagine</label>
        <img class="<?= $this->id ?>_img" src="<?= (!empty($instance['image_uri'])) ? $instance['image_uri'] : ''; ?>" style="margin:0;padding:0;max-width:100%;display:block"/>
        <input type="text" class="widefat <?= $this->id ?>_url" name="<?= $this->get_field_name( 'image_uri' ); ?>" value="<?= $instance['image_uri'] ?? ''; ?>" style="margin-top:5px;" />
        <input type="button" id="<?= $this->id ?>" class="button button-primary js_custom_upload_media" value="Carica Immagine" style="margin-top:5px;" />
    </p>

<?php
    }
}

E il JavaScript per il pulsante di caricamento:

jQuery(document).ready(function ($) {
  function media_upload(button_selector) {
    var _custom_media = true,
        _orig_send_attachment = wp.media.editor.send.attachment;
    $('body').on('click', button_selector, function () {
      var button_id = $(this).attr('id');
      wp.media.editor.send.attachment = function (props, attachment) {
        if (_custom_media) {
          $('.' + button_id + '_img').attr('src', attachment.url);
          $('.' + button_id + '_url').val(attachment.url);
        } else {
          return _orig_send_attachment.apply($('#' + button_id), [props, attachment]);
        }
      }
      wp.media.editor.open($('#' + button_id));
      return false;
    });
  }
  media_upload('.js_custom_upload_media');
});

Ora il tuo widget può far parte di ogni sidebar (ovvero area widget). Per visualizzare una sidebar puoi usare la funzione dynamic_sidebar() che funzionerà ovunque nei tuoi template:

if ( is_active_sidebar('left-sidebar') ) {
    dynamic_sidebar('left-sidebar');
}

Aggiornamento 01/2019: Ho modificato il codice per farlo funzionare con più widget e sidebar.

22 dic 2013 06:24:10
Commenti

Grazie mille per il tuo aiuto! Funziona perfettamente! Apprezzo davvero la tua gentilezza!

keilowe keilowe
22 dic 2013 08:59:57

Grazie mille, ma nel mio widget il caricamento del file si aggiorna solo quando modifico qualcosa all'interno dell'input URL o di un input diverso. Il caricamento dell'immagine non aggiorna questo campo, puoi aiutarmi?

Freestyle09 Freestyle09
25 giu 2020 14:40:43

In qualche modo il mio pulsante per salvare l'immagine era disabilitato da WordPress... Ora funziona perfettamente! Grazie mille!

Freestyle09 Freestyle09
25 giu 2020 16:01:47
0

Ho fatto funzionare la risposta di Svens ma come ha detto alla fine, c'è un problema con gli ID e se hai più uploader in una pagina, cambierà tutti contemporaneamente. Ho iniziato ad avere problemi quando lo usavo per widget nei compositori di pagine e simili. L'ho risolto utilizzando l'ID univoco del widget.

Il mio codice del form era questo:

<label class="widg-label widg-img-label" for="<?php echo $this->get_field_id( 'image_uri' ); ?>">Immagine</label>
<div class="widg-img" >
    <img class="<?php echo $this->get_field_id( 'image_id' ); ?>_media_image custom_media_image" src="<?php if( !empty( $instance['image_uri'] ) ){echo $instance['image_uri'];} ?>" />
    <input input type="hidden" type="text" class="<?php echo $this->get_field_id( 'image_id' ); ?>_media_id custom_media_id" name="<?php echo $this->get_field_name( 'image_id' ); ?>" id="<?php echo $this->get_field_id( 'image_id' ); ?>" value="<?php echo $instance['image_id']; ?>" />
    <input type="text" class="<?php echo $this->get_field_id( 'image_id' ); ?>_media_url custom_media_url" name="<?php echo $this->get_field_name( 'image_uri' ); ?>" id="<?php echo $this->get_field_id( 'image_uri' ); ?>" value="<?php echo $instance['image_uri']; ?>" >
    <input type="button" value="Carica immagine" class="button custom_media_upload" id="<?php echo $this->get_field_id( 'image_id' ); ?>"/>
</div>

e il mio JavaScript era:

jQuery(document ).ready( function(){
    function media_upload( button_class ) {
        var _custom_media = true,
            _orig_send_attachment = wp.media.editor.send.attachment;
         jQuery('body').on('click','.custom_media_upload',function(e) {
            var button_id ='#'+jQuery(this).attr( 'id' );
            var button_id_s = jQuery(this).attr( 'id' ); 
            console.log(button_id); 
            var self = jQuery(button_id);
            var send_attachment_bkp = wp.media.editor.send.attachment;
            var button = jQuery(button_id);
            var id = button.attr( 'id' ).replace( '_button', '' );
            _custom_media = true;

            wp.media.editor.send.attachment = function(props, attachment ){
                if ( _custom_media ) {
                    jQuery( '.' + button_id_s + '_media_id' ).val(attachment.id); 
                    jQuery( '.' + button_id_s + '_media_url' ).val(attachment.url);
                    jQuery( '.' + button_id_s + '_media_image' ).attr( 'src',attachment.url).css( 'display','block' ); 
                } else {
                    return _orig_send_attachment.apply( button_id, [props, attachment] );
                }
            }
            wp.media.editor.open(button);
            return false;
        });
    }
    media_upload( '.custom_media_upload' );

});

Ho principalmente utilizzato il mio ID univoco nel form del widget

<?php echo $this->get_field_id( 'image_id' ); ?>

e l'ho aggiunto davanti alle classi, poi l'ho recuperato senza il #,

var button_id_s = jQuery(this).attr( 'id' ); 

quindi l'ho inserito prima di tutte le classi in modo che corrispondessero al form

jQuery( '.' + button_id_s + '_media_id' ).val(attachment.id); 
jQuery( '.' + button_id_s + '_media_url' ).val(attachment.url);
jQuery( '.' + button_id_s + '_media_image' ).attr( 'src',attachment.url).css( 'display','block' );

Spero che questo aiuti qualcuno che ha lo stesso problema.

10 mag 2017 20:10:18