0

前天,我为我最近的 WordPress 主题开发了一个自定义小部件。在该小部件中,有一个带有其他字段的图像上传字段。我已经完成了所有工作,除了一个问题外,小部件运行良好。当我在侧边栏中拖动小部件并提供所有字段所需的信息时,它在前端显示良好。但在那之后,当我尝试从该小部件后端更改图像时,保存按钮仍然保存。图像不变。

代码如下:

            class Themeslug_About_Widget extends WP_widget{



               public function __construct(){

                        parent::__construct('author_info', esc_html__( 'About Info Box', 'blogista' ), array(

                        'description' => esc_html__( 'About Info Box contain brief about Author/ Company.', 'blogista' ),

                                ));

                        }

                public function widget( $args, $instance ){


                        echo $args['before_widget'];
                            echo $args['before_title'] . $instance['title'] . $args['after_title'];
                            ?>
                            <img src="<?php echo $instance['author_box_image']; ?>" alt="<?php echo $instance['title']; ?>" />
                            <div class="widget-content">

                                <h3 class="title">
                                    <a href="#"><?php echo $instance['author_name']; ?></a>
                                </h3>




                            </div>
                        <?php           
                        echo $args['after_widget'];



                    }

                public function form( $instance ){

                        $title = '';
                        if( !empty( $instance['title'] ) ) {
                            $title = $instance['title'];
                        }


                        $author_box_image = '';

                        if( ! empty( $instance['author_box_image'] ) ) {
                            $author_box_image = $instance['author_box_image'];
                        }
        ?>

                            <p>
                                <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e( 'Title:', 'blogista' ); ?></label>
                                <input type="text" value="<?php echo esc_attr( $title ); ?>" name="<?php echo $this->get_field_name('title'); ?>" id="<?php echo $this->get_field_id('title'); ?>" class="widefat">
                            </p>

                            <p>
                                <button class="button button-primary" id="author_info_image"><?php _e( 'Upload Image', 'blogista' ); ?></button>
                                <input type="hidden" name="<?php echo $this->get_field_name('author_box_image'); ?>" id="<?php echo $this->get_field_id('author_box_image'); ?>"  class="image_link"  value="<?php echo esc_url( $author_box_image ); ?>" >
                                <div class="image_show">
                                    <img src="<?php echo $instance['author_box_image']; ?>" width="200" height="auto" alt="">
                                </div>
                            </p>



                        <?php

                    }

                public function update( $new_instance, $old_instance ) {

                    $instance = array();

                    $instance['title']              = ( ! empty( $new_instance['title'] ) ) ? esc_attr( $new_instance['title'] ) : '';
                    $instance['author_box_image']   = ( ! empty( $new_instance['author_box_image'] ) ) ? esc_url( $new_instance['author_box_image'] ) : '';


                    return $instance;

                }



    }





    function themeslug_admin_enqueue_scrits(){

        wp_enqueue_media();

        wp_enqueue_script( 'admin_custom_script', get_theme_file_uri() . '/js/libs/admin_scripts.js', array( 'jquery' ), '1.0', true );



    }

add_action( 'admin_enqueue_scripts', 'themeslug_admin_enqueue_scrits' );

然后添加下面的jQuery代码:

(function($){


    $(document).ready(function(){
        $('button#author_info_image').on("click",function( e ){

            e.preventDefault();




            var imageUploader = wp.media({

                'title' : 'Upload Author Image',
                'button'    : {
                    'text' : 'Set The Image'
                },
                'multiple' : false

            });


            imageUploader.open();


            imageUploader.on("select", function(){
                var image = imageUploader.state().get("selection").first().toJSON();

                var link = image.url;

                $("input.image_link").val( link );

                $(".image_show img").attr('src', link);

            });


        });
    });




}(jQuery))

第一次一切正常,但是当尝试更改图像时,小部件保存按钮仍然保存。请帮忙。

提前致谢。

4

1 回答 1

1

我会建议您按照我的方式使用图像上传系统创建您的自定义小部件。

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();
}

表单函数将是:

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
}

这是更新功能:

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;
}

如您所见,我在图像输入字段下方添加了一个带有“.upload_image_button”类的按钮,但它现在无法正常工作,要使其正常工作,需要添加我们的自定义管理 JavaScript。

首先需要创建 javascript 文件并将其放入您的主题中,让我们在您的主题文件夹下的 assets/js 中创建一个名为our_admin.js 的文件。

接下来,您将需要注册并将我们的脚本加入队列以使其加载到管理面板中,因此让我们在小部件类构造函数中添加几行:

function __construct() {

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

   parent::__construct(
      'our_widget', // Base ID
      __( 'Our Widget Title', 'text_domain' ), // Name
      array( 'description' => __( 'Our Widget with media files', 'text_domain' ), ) // Args
   );
}

然后您将需要我们的小部件类中的“脚本”功能:

public function scripts()
{
   wp_enqueue_script( 'media-upload' );
   wp_enqueue_media();
   wp_enqueue_script('our_admin', get_template_directory_uri() . '/assets/js/our_admin.js', array('jquery'));
}

如您所见,我添加了 wp_enqueue_script( 'media-upload' ); 和 wp_enqueue_media(); 将媒体库弹出脚本排入队列。

最后,这是一个 js 脚本,它将调用 WordPress 媒体库弹出窗口并将选定的图像放入输入字段:

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();
   });
});

现在比较您的代码,您将看到错误。

我会建议使用插件来显示作者信息以节省您的时间。

于 2018-05-10T18:07:55.893 回答