Wordpress виджеты, использующие вызов jquery - PullRequest
0 голосов
/ 28 октября 2011

Я ищу написать виджет, который пользователь может выбрать из выпадающего меню список веб-значков.При выборе кода виджета должен отображаться предварительный просмотр изображения.Я изо всех сил пытаюсь заставить работать jquery для предварительного просмотра изображения на странице виджета WordPress администратора.

Код виджета выглядит следующим образом

    <?php

class Pretty_Badges extends WP_Widget {

  function Pretty_Badges() {
     /* Widget settings. */
    $widget_ops = array(
      'classname' => 'prettybadges',
      'description' => 'Loved By The Pretty Blog');

     /* Widget control settings. */
    $control_ops = array(
       'width' => 250,
       'height' => 250,
       'id_base' => 'prettybadges-widget');

    /* Create the widget. */
   $this->WP_Widget('prettybadges-widget', 'The Pretty Blog Badges', $widget_ops, $control_ops );

    if(is_admin()) {

    $admin_script_url = WP_PLUGIN_URL . '/love-the-pretty-blog/js/prettyblog.js';
$admin_script_file = WP_PLUGIN_DIR . '/love-the-pretty-blog/js/prettyblog.js';
if(file_exists($admin_script_file)) {
    wp_register_script('tweet-it-script', $admin_script_url);
    wp_enqueue_script('tweet-it-script');
}
    }


  }

  function form ($instance) {
    /* Set up some default widget settings. */

    $defaults = array('badge' => 'default');
    $instance = wp_parse_args( (array) $instance, $defaults ); ?>

  <p>
   <label for="<?php echo $this->get_field_id('badge'); ?>">Select Pretty Badge:</label>
    <p>
    <input type="radio" <?php if (1==$instance['badge']) echo 'checked=checked';?> name="<?php echo $this->get_field_name('badge'); ?>" value="1" />
    <img src="http://theprettyblog.com/wp-content/themes/theprettyblogv2/images/logo.gif"/>
    </p>
    <p>
    <select name="image" id="image" class="inputbox" size="1">
        <option value=""> - Select Image - </option>
        <option value="http://theprettyblog.com/wp-content/themes/theprettyblogv2/images/logo.gif">image1.jpg</option>
        <option value="http://theprettyblog.com/wp-content/themes/theprettyblogv2/images/logo.gif">image2.jpg</option>
        <option value="http://theprettyblog.com/wp-content/themes/theprettyblogv2/images/logo.gif">image3.jpg</option>
    </select>

<div id="imagePreview">

</div>

  </p>

  <?php
}

и файл jquery

    $t = jQuery.noConflict();
$t(function() {

    $t("#image").change(function() {
        var src = $t(this).val();

        $t("#imagePreview").html(src ? "<img src='" + src + "'>" : "");

});    
});
jQuery = jQuery.noConflict();

Благодарю за внимание

Ответы [ 3 ]

2 голосов
/ 02 января 2014

Попробуйте эту функцию

jQuery(document).ready(function() {

        jQuery('body').on('change', '#image', change_image);    

        function change_image(){

             var $src = jQuery(this).find('option:selected').val();
         jQuery('.image_path').attr('src',$src);

        }   
});
1 голос
/ 02 января 2014

После перетаскивания виджета, затем включите функцию jquery, попробуйте эту функцию, очень помогите в полной мере Спасибо;)

jQuery( document ).ajaxComplete( function( event, XMLHttpRequest, ajaxOptions ) {
    // determine which ajax request is this (we're after "save-widget")
    var request = {}, pairs = ajaxOptions.data.split('&'), i, split, widget;
    for( i in pairs ) {
        split = pairs[i].split( '=' );
        request[decodeURIComponent( split[0] )] = decodeURIComponent( split[1] );
    }
    // only proceed if this was a widget-save request
    if( request.action && ( request.action === 'save-widget' ) ) {
        // locate the widget block
        widget = jQuery('input.widget-id[value="' + request['widget-id'] + '"]').parents('.widget');

        // trigger manual save, if this was the save request 
        // and if we didn't get the form html response (the wp bug)
        if( !XMLHttpRequest.responseText ) 
            wpWidgets.save(widget, 0, 1, 0);

        // we got an response, this could be either our request above,
        // or a correct widget-save call, so fire an event on which we can hook our js
        else
           jQuery('body').on('change', '#image', change_image);    

           function change_image(){
            var $src = jQuery(this).find('option:selected').val();
         jQuery('.image_path').attr('src',$src);

        } 
    }
});
1 голос
/ 02 октября 2013

Способ запуска jQuery с WordPress:

jQuery( document ).ready( function( $ ) {
    // do_stuff();
});

Кроме того, вы должны работать с классами вместо идентификаторов, поскольку на странице может быть несколько экземпляров виджетов. sscce :

add_action( 'widgets_init', 'b5f_load_widgets' );

function b5f_load_widgets() {
    register_widget( 'B5F_Example_Widget' );
}    
class B5F_Example_Widget extends WP_Widget {

    private $url;

    function B5F_Example_Widget() {
        $this->url = plugins_url( '/test-me.js', __FILE__ );
        $widget_ops = array( 'classname' => 'example', 'description' => '' );
        $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
        $this->WP_Widget( 'example-widget','Example Widget', $widget_ops, $control_ops );
        if( is_admin() )
            wp_enqueue_script( 
                    'test-me', 
                    $this->url, 
                    array(), // dependencies
                    false, // version
                    true // on footer
            );
    }    

    function widget( $args, $instance ) {
        echo 'Test';
    }

    function update( $new_instance, $old_instance ) {
        return $instance;
    }    

    function form( $instance ) {
        echo "<a href='#' class='test-me'>File to load: {$this->url}</a>";
    }
}

И файл JavaScript.Обратите внимание, что нам нужно добавить прослушиватель Ajax, чтобы исправить ошибку , описанную здесь .

/**
 * Function to execute onClick
 */
function test_click()
{
    var number = 1 + Math.floor( Math.random() * 5000000 );
    jQuery( this ).html( 'Stack Overflow #' + number );
}

/**
 * For widgets already present on page 
 */
jQuery( document ).ready( function( $ ) 
{
    $( '.test-me' ).click( test_click );
});

/**
 * For fresh widgets dropped on the sidebar
 * https://wordpress.stackexchange.com/a/37707/12615
 */
jQuery( document ).ajaxComplete( function( event, XMLHttpRequest, ajaxOptions )
{
    // determine which ajax request is this (we're after "save-widget")
    var request = {}, pairs = ajaxOptions.data.split('&'), i, split, widget;
    for( i in pairs )
    {
        split = pairs[i].split( '=' );
        request[decodeURIComponent( split[0] )] = decodeURIComponent( split[1] );
    }
    // only proceed if this was a widget-save request
    if( request.action && ( request.action === 'save-widget' ) )
    {
        // locate the widget block
        widget = jQuery('input.widget-id[value="' + request['widget-id'] + '"]').parents('.widget');

        // trigger manual save, if this was the save request 
        // and if we didn't get the form html response (the wp bug)
        if( !XMLHttpRequest.responseText ) 
            wpWidgets.save(widget, 0, 1, 0);

        // we got an response, this could be either our request above,
        // or a correct widget-save call, so fire an event on which we can hook our js
        else
            jQuery( '.test-me' ).click( test_click );
    }

});
...