Использование диалогового окна jQuery UI в Wordpress - PullRequest
5 голосов
/ 26 апреля 2011

Я знаю, что на SO есть еще как минимум 1 пост, посвященный этому вопросу, но ответ так и не был точно изложен.

Я работаю в дочерней теме WP в документе head.php.Я добавил это в голову:

<link type="text/css" href="http://www.frontporchdeals.com/wordpress/wp-includes/js/jqueryui/css/ui-lightness/jquery-ui-1.8.12.custom.css" rel="Stylesheet" />  


<?php
    wp_enqueue_style('template-style',get_bloginfo('stylesheet_url'),'',version_cache(),'screen');
    wp_enqueue_script('jquery-template',get_bloginfo('template_directory').'/js/jquery.template.js',array('jquery'),version_cache(), true);
    wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css'); 
    wp_enqueue_script('jq-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.js '); 
    wp_enqueue_script('jq-ui-min', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js' );   
?>

, и я добавил это в теле:

<script>
    jQuery(function() {
        $( "#dialog" ).dialog();
    });
    </script>
<div id="dialog" title="Basic dialog">
    <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

, но без кубиков.Мой div показывает как стандартный div.

Есть идеи вообще?Я знаю, что верхняя таблица стилей должна вызываться с enqueue, но это не должно мешать этому работать.

Ответы [ 3 ]

9 голосов
/ 26 апреля 2011

WordPress jQuery вызывается в бесконфликтном режиме:

jQuery(document).ready(function($) {
  $('#dialog' ).dialog();
});

Также пользовательский интерфейс jQuery загружается перед jQuery. Вы получаете 2 ошибки JavaScript:

Uncaught ReferenceError: jQuery не определен

103Uncaught TypeError: Свойство '$' объекта [объект DOMWindow] не является функцией

Первая ошибка возникает из-за загрузки пользовательского интерфейса jQuery до jQuery, а вторая из-за того, что $ не распознается в бесконфликтном режиме.

Удалите все встроенные теги <script src= и вызов custom.css в заголовке php и добавьте эту функцию в файл functions.php вашей дочерней темы для загрузки сценариев. WordPress разместит их в нужном вам порядке.

add_action( 'init', 'frontporch_enqueue_scripts' );
function frontporch_enqueue_scripts() {
    if (!is_admin() ) {
        wp_enqueue_script( 'jquery' );
        wp_register_script( 'google-jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js', array( 'jquery' ) );
        wp_register_script( 'jquery-template', get_bloginfo('template_directory').'/js/jquery.template.js',array('jquery'),version_cache(), true);
        wp_register_style( 'jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/smoothness/jquery-ui.css', true);
        wp_register_style( 'template-style', 'http://www.frontporchdeals.com/wordpress/wp-includes/js/jqueryui/css/ui-lightness/jquery-ui-1.8.12.custom.css', true); 
        wp_enqueue_style( 'jquery-style' );
        wp_enqueue_style( ' jquery-template' );
        wp_enqueue_script( 'google-jquery-ui' );
        wp_enqueue_script( 'jquery-template' );
    }       
}
1 голос
/ 04 августа 2016

Я создаю собственный плагин для WP admin для вставки данных в пользовательские таблицы MySQL.В течение почти недели я пытался создать диалоговое окно подтверждения события удаления элемента в таблице Wordpress.После того, как я почти потерял все волосы в поисках ответа, это казалось слишком хорошим и простым, чтобы быть правдой.Но сработало.Следует коду.

EDIT : выясняется, что стандартный jquery для wp не работал должным образом, а размещенный в Google jQuery, включенный в другой класс, делал правильные вызовы для JS.Когда я удалил отмененную регистрацию / регистрацию, добавленную ниже, ВСЕ другие диалоги перестали работать.Я не знаю, почему это произошло, или версию jQuery, включенную в этот конкретный дистрибутив WP, но когда я вернулся к старым регистрациям, используя размещенные в Google скрипты, как показано ниже, все вернулось в норму.

ВклPHP (сначала зарегистрируйтесь и вызовите скрипт):

add_action('admin_init', 'init_scripts_2');

function init_scripts_2(){
    ///deregister the WP included jQuery and style for the dialog and add the libs from Google
    wp_deregister_script('jquery-ui');
    wp_register_script('jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js');
    wp_deregister_style('jquery-ui-pepper-grinder');
    wp_register_style('jquery-ui-pepper-grinder', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/pepper-grinder/jquery-ui.min.css');
    wp_enqueue_script('jquery-ui'); ///call the recently added jquery
    wp_enqueue_style('jquery-ui-pepper-grinder'); ///call the recently added style
    wp_deregister_script('prevent_delete'); ///needed the deregister. why? don't know, but worked
    ///register again, localize and enqueue your script
    wp_register_script('prevent_delete',  WP_PLUGIN_URL . '/custom_plugin/js/prevent_delete.js', array('jquery-ui'));
    wp_localize_script('prevent_delete', 'ajaxdelete', array('ajaxurl' => admin_url('admin-ajax.php')));
    wp_enqueue_script('prevent_delete');
}

Далее, если вы открываете диалог по событию щелчка, как я, убедитесь, что вы ВСЕГДА используете класс вместо id, чтобы идентифицировать кнопкуили ссылку позже, на jQuery.

<a class="delete" href="?page=your_plugin&action=delete">Delete</a>

Нам также нужно использовать тег, содержащий текст диалога.Мне нужно было установить стиль, чтобы скрыть div.

<div id="dialog_id" style="display: none;">
    Are you sure about this?
</div>

Наконец, jQuery.

/*jslint browser: true*/
/*global $, jQuery, alert*/
jQuery(document).ready(function ($) {
    "use strict";

    ///on class click
    $(".delete").click(function (e) {
        e.preventDefault(); ///first, prevent the action
        var targetUrl = $(this).attr("href"); ///the original delete call

        ///construct the dialog
        $("#dialog_id").dialog({
            autoOpen: false,
            title: 'Confirmation',
            modal: true,
            buttons: {
                "OK" : function () {
                    ///if the user confirms, proceed with the original action
                    window.location.href = targetUrl;
                },
                "Cancel" : function () {
                    ///otherwise, just close the dialog; the delete event was already interrupted
                    $(this).dialog("close");
                }
            }
        });

        ///open the dialog window
        $("#dialog_id").dialog("open");
    });
});

EDIT : вызов стандартного стиля диалога wpне работал в конце концов.Благодаря стилю «перец-мельница» диалоговое окно правильно отображалось в центре окна.Я знаю, что внешний вид диалогового окна не очень прост, но мне нужно было диалоговое окно подтверждения, и это сработало для меня.

0 голосов
/ 26 апреля 2011

Диалоговое окно div создается ПОСЛЕ того, когда вы пытаетесь воздействовать на него. Вместо этого вы должны использовать:

$(document).ready(function() {
  $( "#dialog" ).dialog();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...