web-dev-qa-db-ja.com

プラグインでjQuery UIを使用する方法

私がGoogleで何かをしても何も返されないのは、世界で悲しい日です。デフォルトの日付ピッカー(または現時点では任意の日付ピッカー)を使用しようとしていますが、Wordpress/PHPに関する知識がないために使用できません。私のプラグインで、私はjqueryとuiを登録しようとしていて、どうやらその過程でWordPressの他の部分を壊しています。誰かが私が何をしているのか教えてもらえますか?彼らが実用的な解決策を提供できるのであれば、私は私のコードをすべて廃棄します。

add_action('init', 'add_styles');

function add_styles(){
    wp_deregister_style('simpleschoolstyles');
    wp_register_style('simpleschoolstyles', SSM_STYLEFILE);

    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js');

    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' );
    wp_register_style( 'jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/pepper-grinder/jquery-ui.min.css' );

    wp_deregister_script('maskedinput');
    wp_register_script('maskedinput', SSM_PLUGIN_URL . '/includes/js/jquery.maskedinput.min.js');

    wp_deregister_script('simpleschool');
    wp_register_script('simpleschool', SSM_PLUGIN_URL . '/includes/js/simpleschool.js');
}

add_action('wp_enqueue_scripts', 'load_scripts');
add_action('admin_enqueue_scripts', 'load_scripts');

function load_scripts()
{
    wp_enqueue_style('jquery-ui');    
    wp_enqueue_style('simpleschoolstyles');
    wp_enqueue_script('jquery');       
    wp_enqueue_script('jquery-ui');
    wp_enqueue_script('maskedinput');
    wp_enqueue_script('simpleschool');
}

ユーザーデータ入力のためのフロントエンドだけでなく管理領域でも利用できるようにjQueryが必要です。誰かが助けてください。すでに髪の毛を全部切り取っているので足の爪を引っ張るところです。間違った時点でキューに入れているに違いないと思っていますが、WordPressに関する知識が限られていたため、自分で掘ったすぐに墓.

更新: 私は自分のスクリプトを修正し、jQuery UIをロードするだけで、jQueryとUIの両方がロードされ、これら2つで成功することをテストしました。

add_action('init', 'init_scripts');

function init_scripts(){
    wp_deregister_style('simpleschoolstyles');
    wp_register_style('simpleschoolstyles', SSM_STYLEFILE);

    //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' );
    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_deregister_script('maskedinput');
    wp_register_script('maskedinput', SSM_PLUGIN_URL . '/includes/js/jquery.maskedinput.min.js');

    //wp_deregister_script('simpleschool');
    wp_register_script('simpleschool', SSM_PLUGIN_URL . '/includes/js/simpleschool.js');

    wp_enqueue_style('jquery-ui-pepper-grinder');
    wp_enqueue_style('simpleschoolstles');
    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'jquery-ui' );
    wp_enqueue_script('simpleschool');
}

私のテスト:

jQuery(document).ready(function(){
    //jQuery('.datepick').mask("99/99/9999");
    //jQuery('.phone').mask("(999) 999-9999");
    jQuery( '.datepick' ).datepicker( 'option', 'dateFormat', 'yyyy-mm-dd' ); // <-- this fails ????    
    alert('jQuery BETTER BE LOADED!!!'); // <---this worked
    jQuery('<div>crazy wordpress and their php</div>').dialog(); // <--- this worked too
});
8
clockwiseq

Datepicker に必要なすべてのライブラリがWordPress にバンドルされており、すべての適切な依存関係を持つ registered であることを考えると、本当に必要なのは次のとおりです。

function enqueue_my_scripts_wpse_97533() {
  wp_enqueue_script('jquery-ui-datepicker');
}
add_action('wp_enqueue_scripts','enqueue_my_scripts_wpse_97533');

次にページのソースを見ると、jQuery、jQuery-UI、およびjQuery-UI-Datepickerがすべてロードされていることがわかります。

もちろん、他のスクリプトを自分のものと同じくらい早い方法で自分でロードする必要がありますが、それらを依存関係(3番目のパラメーター)で登録する必要があります。

wp_register_script( $handle, $src, $deps, $ver, $in_footer ); 

例えば...

wp_register_script(
    'maskedinput',
    SSM_PLUGIN_URL.'/includes/js/jquery.maskedinput.min.js',
    array('jquery')
);

そのように、あなたはそれをロードすることができます...

function enqueue_my_scripts_wpse_97533_v2() {
  wp_enqueue_script('maskedinput');
}
add_action('wp_enqueue_scripts','enqueue_my_scripts_wpse_97533_v2');

...そして依存関係jQueryが同様にロードされることを知っています。

9
s_ha_dum

@ s_ha_dumの優秀な答え を補足するために、プラグインページで組み込みのjQuery UI日付ピッカーを使用する方法を示す例を示します。

結果は次のようになります。

enter image description here

GitHubでダウンロード

最も重要な部分:

  • オプションページのスラッグを使用して、すべての管理ページ( background )ではなく、自分のページにのみスクリプトとスタイルシートをエンキューします。
  • datepicker({ dateFormat: "yy-mm-dd" })を必ず設定してください。そうすれば、コールバックハンドラに何を期待すべきかがわかります。
  • WordPressの日付ピッカーには組み込みのスタイルはありませんので、別のスタイルシートをエンキューする必要があります。しかし、CSSの @helenhousandi からの Nice demo plugin もあり、コアスタイルにうまく適合しています。

最初に基本クラスを作成して、他の回答でも使用できるものを用意し、日付選択スクリプトの実際のコードを具体的かつ単純にしています。

基本クラスWpse_Plugin_Options_Page

/**
 * Basic code, for a better documented example see
 * @link {https://github.com/toscho/T5-Admin-Menu-Demo}
 * @author toscho
 *
 * We do not use the so called Settings API here, because that is way too
 * complicated.
 * admin-post.php is used instead: simple, clean markup, works.
 */
class Wpse_Plugin_Options_Page
{
    protected static $instance = NULL;
    protected $slug      = '';
    protected $menu_slug = 'wpse_demo';
    protected $option    = 'wpse_option';
    protected $title     = 'WPSE Demo';
    protected $styles    = array();
    protected $scripts   = array();

    public static function get_instance()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    public function wp_loaded()
    {
        add_action(
            "admin_post_update_$this->option",
            array ( $this, 'admin_post' )
        );
        add_action(
            'admin_menu',
            array ( $this, 'admin_menu' )
        );
    }

    public function admin_menu()
    {
        $slug = add_options_page(
            $this->title,                       // page title
            $this->title,                       // menu title
            'manage_options',                   // capability
            $this->menu_slug,                   // menu slug
            array ( $this, 'render_page_base' ) // callback function
        );

        $this->slug = $slug;

        add_action( "admin_print_styles-$slug",  array ( $this, 'enqueue_style' ) );
        add_action( "admin_print_scripts-$slug", array ( $this, 'enqueue_script' ) );
        add_action( "page_content_$slug",        array ( $this, 'render_page_content' ) );
    }

    public function render_page_base()
    {
        $this->print_message();

        printf(
            '<div class="wrap"><h2>%1$s</h2><form method="post" action="%2$s">',
            $GLOBALS['title'],
            admin_url( 'admin-post.php' )
        );

        printf(
            '<input type="hidden" name="action" value="%s"/>',
            "update_$this->option"
        );
        wp_nonce_field( "update_$this->option" );

        do_action( 'page_content_' . $this->slug );

        print '</form></div>';
    }

    protected function print_message()
    {
        if ( ! isset ( $_GET['msg'] ) )
            return;

        $text = $this->get_message_text( $_GET['msg'] );

        if ( ! $text )
            return;

        print "<div id='message' class='updated fade'><p>$text</p></div>";
    }

    protected function get_message_text( $id )
    {
        $messages = $this->get_messages();

        if ( isset ( $messages[ $id ] ) )
            return $messages[ $id ];

        return FALSE;
    }

    protected function get_messages()
    {
        return array();
    }

    public function render_page_content()
    {
        echo $this->slug;
    }

    public function enqueue_style()
    {
        foreach ( $this->styles as $style )
            wp_enqueue_style( $style );

        do_action( 'base_styles_loaded_' . $this->slug );
    }

    public function enqueue_script()
    {
        foreach ( $this->scripts as $script )
            wp_enqueue_script( $script );

        do_action( 'base_scripts_loaded_' . $this->slug );
    }

    public function admin_post()
    {
        if ( ! check_admin_referer( "update_$this->option" ) )
            die( 'nope' );

        if ( ! isset ( $_POST[ $this->option ] ) )
            die( 'something is missing' );

        $msg = $this->save_option( $_POST[ $this->option ] );

        $url = add_query_arg( 'msg', $msg, $_POST[ '_wp_http_referer' ] );

        wp_safe_redirect( $url, 303 );
        exit;
    }

    protected function save_option( $data )
    {
        return (bool) update_option( $this->option, $data );
    }
}

今、私たちは最も重要な部分だけを再定義しなければなりません。素敵で短いです。

特別クラスWpse_Datepicker_Example

class Wpse_Datepicker_Example extends Wpse_Plugin_Options_Page
{
    protected $title     = 'jQuery Date Picker';
    protected $menu_slug = 'wpse_datepicker';
    protected $option    = 'wpse_datepicker';
    protected $scripts   = array ( 'jquery-ui-datepicker' );

    // not inherited
    public static function get_instance()
    {
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;
    }

    public function render_page_content()
    {
        $value = esc_attr( get_option( $this->option ) );
        printf(
            '<p style="margin:100px auto;width:30em"><label for="%1$s">Pick a date
                <input type="text" id="%1$s" name="%2$s" value="%3$s" />
            </label> %4$s</p>',
            'datepicker',
            $this->option,
            $value,
            get_submit_button( 'Save', 'primary', 'submit', FALSE )
        );

        add_action(
            "admin_footer-$this->slug",
            array ( $this, 'print_footer_script' )
        );
    }

    public function enqueue_style()
    {
        wp_register_style(
            'jquery-ui-datepicker',
            'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/pepper-grinder/jquery-ui.min.css'
        );
        wp_enqueue_style( 'jquery-ui-datepicker' );
    }

    public function print_footer_script()
    {
        ?>
<script>
jQuery( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
</script>
        <?php
    }

    protected function get_messages()
    {
        return array (
            1 => 'Date saved.'
        );
    }
}

まだ改善の余地がありますが、最初はそれが役に立つはずです。

6
fuxia

JQueryをテーマに含める方法はいくつかあります。私はいつもWPバンドル版を使っていますが、とても単純です。適切に設定するために、WP pageがページロードに含まれるべき以下のファイルを持つことを確認する必要があります。ベローズスクリプトとスタイルをロードするには、テーマfunctions.phpファイルにベローズコードを追加します。

フロントエンド用のスクリプト

function add_e2_date_picker(){
//jQuery UI date picker file
wp_enqueue_script('jquery-ui-datepicker');
//jQuery UI theme css file
wp_enqueue_style('e2b-admin-ui-css','http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css',false,"1.9.0",false);
}
add_action('wp_enqueue_scripts', 'add_e2_date_picker'); 

バックエンド用のスクリプト

function add_e2_date_picker(){
//jQuery UI date picker file
wp_enqueue_script('jquery-ui-datepicker');
//jQuery UI theme css file
wp_enqueue_style('e2b-admin-ui-css','http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css',false,"1.9.0",false);
}
add_action('admin_enqueue_scripts', 'add_e2_date_picker'); 

Single.php、page、plugin pageなど、特定のページにフックする関数を書くことができます。 Settigns - > Date Picker に表示するために 'options-general.php'を追加またはフックしました。このコードにもfuntions.phpファイルを追加するか、それらのコードを使用してください。

function register_datepiker_submenu() {
    add_submenu_page( 'options-general.php', 'Date Picker', 'Date Picker', 'manage_options', 'date-picker', 'datepiker_submenu_callback' );
}

function datepiker_submenu_callback() { ?>

    <div class="wrap">

    <input type="text" class="datepicker" name="datepicker" value=""/>

    </div>

    <script>
    jQuery(function() {
        jQuery( ".datepicker" ).datepicker({
            dateFormat : "dd-mm-yy"
        });
    });
    </script> 

<?php }
add_action('admin_menu', 'register_datepiker_submenu');

?>

このコードを追加すると、 [管理者メニュー] - > [設定] - > [日付ピッカー] に日付選択機能が追加されます。このオプションを入手するのに手助けが必要な場合は、 jQueryのDatePickerをWordPressテーマまたはプラグインに追加してください にコメントを付けてください。

2
csehasib