0
votes

I'm trying to create a custom WordPress widget that lets the user select an image, link, and title. The widget will be displayed as an advertisement image in the sidebar. This is the code:

PHP:

<?php


class Ad extends WP_Widget {

public function __construct() {
    parent::__construct(
        'widget-ad',
        'Advertisement',
        array(
            'description' => 'Advertisement Widget',
            'classname'   => 'widget-ad',
        ) );
}

public function widget( $args, $instance ) {
    ...
}

public function form( $instance ) {
    $title       = ! empty( $instance['title'] ) ? $instance['title'] : '';
    $url         = ! empty( $instance['url'] ) ? $instance['url'] : '';
    $image_url         = ! empty( $instance['image_url'] ) ? $instance['image_url'] : '';
    ?>
    <p>
        <label
                for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
            Title:
        </label>
        <input
                class="widefat"
                id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
                name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
                type="text"
                value="<?php echo esc_attr( $title ); ?>">
    </p>
    <p>
        <label
                for="<?php echo esc_attr( $this->get_field_id( 'url' ) ); ?>">
            URL:
        </label>
        <input
                class="widefat"
                id="<?php echo esc_attr( $this->get_field_id( 'url' ) ); ?>"
                name="<?php echo esc_attr( $this->get_field_name( 'url' ) ); ?>"
                type="text"
                value="<?php echo esc_attr( $url ); ?>"
                dir="ltr">
    </p>
    <p>
        <img
             class="image-fluid"
             id="<?php echo esc_attr( $this->get_field_id( 'image_url' ) ) . "-img"; ?>"
             src="<?php echo esc_url( $image_url ); ?>"
             alt="" />
        <input type="text"
               id="<?php echo esc_attr( $this->get_field_id( 'image_url' ) ); ?>"
               name="<?php echo esc_attr( $this->get_field_name( 'image_url' ) ); ?>"
               value="<?php echo esc_url( $image_url ); ?>" />
        <br>
        <a href="#" class="button js-select-media"
           data-target="<?php echo esc_attr( $this->get_field_id( 'image_url' ) ); ?>">
            Select Image
        </a>
        <a href="#" class="button js-remove-media"
           data-target="<?php echo esc_attr( $this->get_field_id( 'image_url' ) ); ?>">
            Remove Image
        </a>
    </p>
    <?php
}

public function update( $new_instance, $old_instance ) {
    $instance                = array();
    $instance['title']       = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
    $instance['url']         = ( ! empty( $new_instance['url'] ) ) ? strip_tags( $new_instance['url'] ) : '';
    $instance['image_url']         = ( ! empty( $new_instance['image_url'] ) ) ? strip_tags( $new_instance['image_url'] ) : '';

    return $instance;
}
}

/**
 * Register Widget
 */
add_action( 'widgets_init', function() {
    register_widget( 'Ad' );
});

JavaScript:

$(document).ready(() => {

    // Open WP media selector
    $(document).on('click', '.js-select-media', (e) => {
        e.preventDefault();
        const target_id = $(e.target).data('target');
        const input_element = $('#' + target_id);
        const img_element = $('#' + target_id + '-img');
        const image = wp.media({
            title: 'Select An Image',
            multiple: false,
            library: { 
                type: 'image'
            },
            button: {
                text: 'Select'
            },
        }).open().on('select', (e) => {
            const image_url = image.state().get('selection').first().toJSON().url;
            input_element.val(image_url).trigger('change');
            img_element.attr('src', image_url);
        });
    });

    // Remove selected Image
    $(document).on('click', '.js-remove-media', (e) => {
        e.preventDefault();
        const element = $(e.target);
        const target_id = element.data('target');
        $('#' + target_id).val('').trigger('change');
        $('#' + target_id + '-img').attr('src', '');
    });

Problem:

In the admin area of the WordPress site, when I select an image or remove a selected one, the widget's save button doesn't get enabled (it doesn't detect the value change of the image input field). I tried everything. I don't know what's the problem.

2

2 Answers

1
votes

After going through WordPress files (PHP and JS) I came across a function that seemed to be responsible for saving Widgets (using Ajax requests).

Location:

website-root\wp-admin\js\widgets.js

It defines an object named wpWidgets on the window object so it's available globally. On line 529 wpWidgets defines a function with this signature:

save : function( widget, del, animate, order ) { ... }

widget argument is a div element with the widget class.

So in my JavaScript I called it like this to manually save the widget:

wpWidgets.save( input_element.closest('div.widget'), 0, 1, 0 );
1
votes

Ran into the same problem. What I ended up doing was using JavaScript to change the value and status of the save button on the admin page in the same function that I am updating the input box.

var save_Button = document.getElementById("widget-downloader_widget-2-savewidget");
save_Button.disabled = false;
save_Button.value = "Save";

It may not be the best solution but just enabling the save button within the JS function that is updating the image url has been working for me.