При загрузке изображения изображение не меняется, но URL изображения правильный

Я пробую WordPress виджеты, и я взял этот код из https://vedmant.com/using-wordpress-media-library-in-widgets-options/. Предполагается, что виджет позволяет загружать ваши собственные изображения через медиатеку WordPress. Код работает, чтобы открыть библиотеку мультимедиа, загрузить изображение и выбрать его, но изображение не изменится, чтобы показать новое изображение.

Вот код (также на сайте):

Я прочитал некоторые другие шаги по подобным вещам и попытался найти обновляющие виджеты, но я не могу найти ответ, который ищу. Я думаю, проблема в том, что текстовое поле будет заполнено URL-адресом изображения, но не будет обновляться, потому что WordPress не думает, что ничего не изменилось. Любые идеи о том, что я могу сделать?

<?php
add_action( 'widgets_init', 'myw_init' );

function myw_init() {
register_widget( 'my_widget' );
}

class my_widget extends WP_Widget {

/**
* Sets up the widgets name etc
*/
function __construct() {

// Add Widget scripts
add_action('admin_enqueue_scripts', array($this, 'scripts'));

parent::__construct(
'my_widget', // Base ID
__( 'Our Widget Title', 'text_domain' ), // Name
array( 'description' => __( 'Our Widget with media files', 'text_domain' ), ) // Args
);
}
/**
* Enqueue scripts
*/
public function scripts()
{
wp_enqueue_script( 'media-upload' );
wp_enqueue_media();
wp_enqueue_script('mfc-media-upload', get_template_directory_uri() . '/../../plugins/my-featured-content/mfc-media-upload.js', array('jquery'));
}

/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// Our variables from the widget settings
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Default title', 'text_domain' ) : $instance['title'] );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';

ob_start();
echo $args['before_widget'];
if ( ! empty( $instance['title'] ) ) {
echo $args['before_title'] . $title . $args['after_title'];
}
?>

<?php if($image): ?>
<img src="<?php echo esc_url($image); ?>" alt="">
<?php endif; ?>

<?php
echo $args['after_widget'];
ob_end_flush();
}

/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
$image = ! empty( $instance['image'] ) ? $instance['image'] : '';
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'image' ); ?>"><?php _e( 'Image:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'image' ); ?>" name="<?php echo $this->get_field_name( 'image' ); ?>" type="text" value="<?php echo esc_url( $image ); ?>" />
<button class="upload_image_button button button-primary">Upload Image</button>
</p>
<?php
}

/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*
* @return array
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
$instance['image'] = ( ! empty( $new_instance['image'] ) ) ? $new_instance['image'] : '';

return $instance;
}
}

И для JQuery:

jQuery(document).ready(function ($) {

$(document).on("click", ".upload_image_button", function (e) {
e.preventDefault();
var $button = $(this);// Create the media frame.
var file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select or upload image',
library: { // remove these to show all
type: 'image' // specific mime
},
button: {
text: 'Select'
},
multiple: false  // Set to true to allow multiple files to be selected
});

// When an image is selected, run a callback.
file_frame.on('select', function () {
// We set multiple to false so only get one image from the uploader

var attachment = file_frame.state().get('selection').first().toJSON();

$button.siblings('input').val(attachment.url);

});

// Finally, open the modal
file_frame.open();
});
});

0

Решение

Вы можете добавить параметр запроса к URL-адресу изображения, чтобы сделать его уникальным, например:

<img src="<?php echo esc_url($image); ?>?<?php echo time() ?>" alt="">

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector