WordPress的自定义小部件图片上传 [英] Wordpress custom widget image upload

查看:136
本文介绍了WordPress的自定义小部件图片上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我忙于构建我自己的Wordpress Widget。除了Wordpress媒体上传程序,一切正常。
我创建了八个按钮和八个输入文本字段,其中应包含已上传图片的网址。



点击事件未被触发,可能是因为Wordpress输出了两次HTML(一次在可用小部件栏中,一次在栏中当前活动小部件)。

有没有人看到我在做什么错误?



下面你可以找到我的代码。



感谢您的帮助!

 <?php 
/ *
插件名称:Home_Rollover_Widget
插件URI:
描述:Home Rollover Widget
版本:1.0
作者:
作者URI:
* /

//初始化小部件
add_action('widgets_init',array('Home_Rollover_Widget','register'));
$ b $ **
* Home_Rollover_Widget
*
* @package
* @author
* @copyright 2012
* @版本$ Id $
* @access public
* /
class Home_Rollover_Widget extends WP_Widget
{
/ **
* __construct()
*
* @return void
* /
public function __construct()
{
parent :: __ construct('home-rollover-widget');
$ b $ **
* control()
*
* @return void
* /
public function control()
{
// Load upload thickbox script
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');

//加载厚盒CSS
wp_enqueue_style('thickbox');

//载入所有部件选项
$ data = get_option('Home_Rollover_Widget');
?>

<! - 小工具标题 - >
< p>< label> Titel< input name =home_rollover_widget_titletype =textvalue =<?php echo $ data ['home_rollover_widget_title'];?> />< /标签>< / p为H.

<?php
//如果提供了标题,请更新它。
if(isset($ _ POST ['home_rollover_widget_title'])){
$ data ['home_rollover_widget_title'] = attribute_escape($ _ POST ['home_rollover_widget_title']);
}

//显示图像URL和文本的8个输入组
($ i = 1; $ i <= 8; ++ $ i)
{
?>

< p>< a href =#id =upload-button-<?php echo $ i;?>>上传图片< / a>< p为H.
< p>< label> IMAGE<?php echo $ i; ?>< input id =home_rollover_widget_image_url_<?php echo $ i;?> name =home_rollover_widget_image_url_<?php echo $ i;?> type =textvalue =<?php echo $ data ['home_rollover_widget_image_url _'。$ i];?> />< /标签>< / p为H.
< p>< label> TEXT<?php echo $ i; ?>< input name =home_rollover_widget_text_<?php echo $ i;?> type =textvalue =<?php echo $ data ['home_rollover_widget_text _'。$ i];?> />< /标签>< / p为H.
<?php
//如果提供了一个URL,请更新它。
if(isset($ _ POST ['home_rollover_widget_image_url _'。$ i])){
$ data ['home_rollover_widget_image_url_1'] = attribute_escape($ _ POST ['home_rollover_widget_image_url _'。$ i]);
}

//如果提供了文本,请更新它。
if(isset($ _ POST ['home_rollover_widget_text _'。$ i])){
$ data ['home_rollover_widget_text_1'] = attribute_escape($ _ POST ['home_rollover_widget_text _'。$ i]);
}

?>

< script type =text / javascript>
var formField ='';
var imgUrl ='';

jQuery(document).ready(function(){
jQuery('#upload-button-<?php echo $ i;?>')。click(function() {
alert('点击上传按钮');
formField = jQuery('#upload-button-<?php echo $ i;?>')。attr('name');
tb_show('','media-upload.php?type = image& amp& amp; amp; TB_iframe = 1');
return false;
});

//发送url到插件编辑器
window.send_to_editor = function(html){
imgUrl = jQuery('img',html).attr('src');
alert('发送图像url'+ imgUrl +'到文本框');
jQuery('#home_rollover_widget_image_url_<?php echo $ i;?>').val(imgUrl);
tb_remove();
}
});
< / script>

< hr />

<?php
}

//更新小部件数据
update_option('Home_Rollover_Widget',$ data);

$ b / **
* widget()
*
* @param mixed $ args
* @return void
* /
函数构件($ args)
{
//载入所有构件选项
$ data = get_option('Home_Rollover_Widget');
?>

< h4><?php echo $ data ['home_rollover_widget_title']; ?>< / H4>

< div id =all> ($ i = 1; $ i <= 8; ++ $ i)
($ b $)
//循环元件元素
b //查找图片URL
$ imageUrl = $ data ['home_rollover_widget_image_url _'。$ i];

//检查第一个斜杠,如果不存在,则添加它。
if(substr($ imageUrl,0,1)!='/'){
$ imageUrl ='/'.$imageUrl;
}
?>
< ul>
< li>< a href =#>< img src =<?php echo get_template_directory_uri();?><?php echo $ imageUrl;?> />< h4><?php echo $ data ['home_rollover_widget_text _'。$ i]; ?>< / H4>< / A>< /锂>
< / ul>
<?php
}
?>
< / div>

$ b $ **
$ b $ **
$ register $(

* @return void
* /
函数寄存器()
{
//注册边栏
register_sidebar_widget('Home Rollover Widget',array('Home_Rollover_Widget','widget'));

//注册控制面板
register_widget_control('Home Rollover Widget',array('Home_Rollover_Widget','control'));
}
}


解决方案

I为这个例子简化了这个小部件,删除了for循环,因为我认为你可以创建这个小部件的新实例。这也允许对物品进行分类的附加好处。我将js移动到了另一个文件,因为不需要重复代码。



小部件类

  class Home_Rollover_Widget extends WP_Widget 
{

public function __construct()
{
parent :: __ construct(
'home '
'首页滚动小部件',
数组(
'description'=>'主页滚动小部件'

);
}

公共函数部件($ args,$ instance)
{
//这个例子的基本输出
echo'< a href = # >
< img src ='。esc_url($ instance ['image_uri'])。'/>
< h4> ;. esc_html($ instance ['image_uri'])。'< / h4>
< / a>';
}

公共函数形式($ instance)
{
//移除for循环,您可以创建widget的新实例,而不是
? >
< p>
< label for =<?php echo $ this-> get_field_id('text');?>>文字< / label>< br />
< input type =textname =<?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');?>>图片< / label>< br />
< input type =textclass =imgname =<?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 =buttonclass =select-imgvalue =Select Image/>
< / p>
<?php
}


}
//结束类

//初始化小部件
add_action('widgets_init',create_function('','return register_widget(Home_Rollover_Widget);'));
$ b $ // //排队必要的js
函数hrw_enqueue()
{
wp_enqueue_style('thickbox');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
//将js移至外部文件,您可能需要更改路径
wp_enqueue_script('hrw','/wp-content/plugins/home-rollover-widget/script.js', null,null,true);
}
add_action('admin_enqueue_scripts','hrw_enqueue');

新的js文件:使用 .on()方法而不是 .click()来附加事件处理程序。

  var image_field; 
jQuery(function($){
$(document).on('click','input.select-img',function(evt){
image_field = $(this))。 ('。img');
tb_show('','media-upload.php?type = image& amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp;
window.send_to_editor = function(html){
imgurl = $('img',html).attr('src');
image_field.val(imgurl);
tb_remove();
}
});


I'm busy with building my own Wordpress Widget. Everything works fine except for the Wordpress media up loader. I have created eight buttons and eight input text fields which should contain the url of the image that has been uploaded.

The click event is not being fired, probably because Wordpress outputs the HTML twice(Once in the bar of the available widgets and once in the bar currently active widgets).

Does anybody sees what I'm doing wrong?

Below you find my code.

Thanks in advance for the help!

<?php
/*
Plugin Name: Home_Rollover_Widget
Plugin URI: 
Description: Home Rollover Widget
Version: 1.0
Author: 
Author URI: 
*/

// Initialize widget
add_action('widgets_init', array('Home_Rollover_Widget', 'register'));

/**
 * Home_Rollover_Widget
 * 
 * @package 
 * @author 
 * @copyright 2012
 * @version $Id$
 * @access public
 */
class Home_Rollover_Widget extends WP_Widget
{   
    /**
     * __construct()
     * 
     * @return void
     */
    public function __construct()
    {
        parent::__construct('home-rollover-widget');
    }
    /**
     * control()
     * 
     * @return void
     */
    public function control()
    {    
        // Load upload an thickbox script
        wp_enqueue_script('media-upload');
        wp_enqueue_script('thickbox');

        // Load thickbox CSS
        wp_enqueue_style('thickbox');

        // Load all widget options
        $data = get_option('Home_Rollover_Widget');
        ?>

        <!-- Widget title -->
        <p><label>Titel<input name="home_rollover_widget_title" type="text" value="<?php echo $data['home_rollover_widget_title']; ?>" /></label></p>

        <?php
        // If there's a title provided, update it.
        if (isset($_POST['home_rollover_widget_title'])){
            $data['home_rollover_widget_title'] = attribute_escape($_POST['home_rollover_widget_title']);
        }

        // Show 8 input groups for image URL and text
        for ($i = 1; $i <= 8; ++$i)
        {
            ?>

            <p><a href="#" id="upload-button-<?php echo $i; ?>">UPLOAD IMAGE</a></p>
            <p><label>IMAGE <?php echo $i; ?><input id="home_rollover_widget_image_url_<?php echo $i; ?>" name="home_rollover_widget_image_url_<?php echo $i; ?>" type="text" value="<?php echo $data['home_rollover_widget_image_url_'.$i]; ?>" /></label></p>
            <p><label>TEXT <?php echo $i; ?><input name="home_rollover_widget_text_<?php echo $i; ?>" type="text" value="<?php echo $data['home_rollover_widget_text_'.$i]; ?>" /></label></p>
            <?php
            // If there's an URL provided, update it.
            if (isset($_POST['home_rollover_widget_image_url_'.$i])){
                $data['home_rollover_widget_image_url_1'] = attribute_escape($_POST['home_rollover_widget_image_url_'.$i]);
            }

            // if there's a text provided, update it.
            if (isset($_POST['home_rollover_widget_text_'.$i])) {
                $data['home_rollover_widget_text_1'] = attribute_escape($_POST['home_rollover_widget_text_'.$i]);
            }

            ?>

            <script type="text/javascript">            
                var formField = '';
                var imgUrl ='';

                jQuery(document).ready(function() {
                    jQuery('#upload-button-<?php echo $i; ?>').click(function() {
                        alert('Clicked on upload button');
                        formField = jQuery('#upload-button-<?php echo $i; ?>').attr('name');
                        tb_show('', 'media-upload.php?type=image&amp&TB_iframe=1');
                        return false;
                    });

                    // send url back to plugin editor
                    window.send_to_editor = function(html) {
                        imgUrl = jQuery('img',html).attr('src');
                        alert('Sending image url'+imgUrl+' to text field');
                        jQuery('#home_rollover_widget_image_url_<?php echo $i; ?>').val(imgUrl);
                        tb_remove();
                    }            
                });
            </script>

            <hr />

            <?php    
        }

        // Update widget data
        update_option('Home_Rollover_Widget', $data);
    }

    /**
     * widget()
     * 
     * @param mixed $args
     * @return void
     */
    function widget($args)
    {           
        // Load all widget options
        $data = get_option('Home_Rollover_Widget');        
        ?>

        <h4><?php echo $data['home_rollover_widget_title']; ?></h4>

        <div id="all">
            <?php
            // Loop though the widget elements
            for ($i = 1; $i <= 8; ++$i) 
            {
                // Find image URL
                $imageUrl = $data['home_rollover_widget_image_url_'.$i];

                // Check for first slash, if not present, add it.
                if (substr($imageUrl, 0, 1) != '/') {
                    $imageUrl = '/'.$imageUrl;
                }
                ?>
                <ul>
                    <li><a href="#"><img src="<?php echo get_template_directory_uri(); ?><?php echo $imageUrl; ?>" /><h4><?php echo $data['home_rollover_widget_text_'.$i]; ?></h4></a></li>      
                </ul>
                <?php
            }
            ?>
        </div>
        <?php
    }

    /**
     * register()
     * 
     * @return void
     */
    function register()
    {
        // Register for sidebar
        register_sidebar_widget('Home Rollover Widget', array('Home_Rollover_Widget', 'widget'));

        // Register for control panel
        register_widget_control('Home Rollover Widget', array('Home_Rollover_Widget', 'control'));
    }
}

解决方案

I have simplified the widget a little for this example, removing the for loop as I think you could just create new instances of the widget. This also allows the added benefit of sorting the items. I moved the js to another file as there's no need to repeat the code.

The widget class

class Home_Rollover_Widget extends WP_Widget
{

  public function __construct()
  {
    parent::__construct(
      'home-rollover-widget',
      'Home Rollover Widget',
      array(
        'description' => 'Home rollover widget'
      )
    );
  }

  public function widget( $args, $instance )
  {
    // basic output just for this example
    echo '<a href="#">
      <img src="'.esc_url($instance['image_uri']).'" />
      <h4>'.esc_html($instance['image_uri']).'</h4>
    </a>';
  }

  public function form( $instance )
  {
    // removed the for loop, you can create new instances of the widget instead
    ?>
    <p>
      <label for="<?php echo $this->get_field_id('text'); ?>">Text</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'); ?>">Image</label><br />
      <input type="text" class="img" 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" class="select-img" value="Select Image" />
    </p>
    <?php
  }


} 
// end class

// init the widget
add_action( 'widgets_init', create_function('', 'return register_widget("Home_Rollover_Widget");') );

// queue up the necessary js
function hrw_enqueue()
{
  wp_enqueue_style('thickbox');
  wp_enqueue_script('media-upload');
  wp_enqueue_script('thickbox');
  // moved the js to an external file, you may want to change the path
  wp_enqueue_script('hrw', '/wp-content/plugins/home-rollover-widget/script.js', null, null, true);
}
add_action('admin_enqueue_scripts', 'hrw_enqueue');

New js file: use the .on() method instead of .click() to attach the event handler.

var image_field;
jQuery(function($){
  $(document).on('click', 'input.select-img', function(evt){
    image_field = $(this).siblings('.img');
    tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
    return false;
  });
  window.send_to_editor = function(html) {
    imgurl = $('img', html).attr('src');
    image_field.val(imgurl);
    tb_remove();
  }
});

这篇关于WordPress的自定义小部件图片上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆