web-dev-qa-db-fra.com

Comment sélectionner le contenu dans la vue texte textrea dans wp_editor?

J'essaie de compter les mots parmi d'autres statistiques textuelles saisies dans l'éditeur de publication par défaut (wp_editor).

Il est supposé que le mot d'écriture compte dans <div id = "Nombre de mots">dans la boîte de méta juste en dessous de wp_editor.

J'ai pu sélectionner correctement l'éditeur visuel copiermais pas l'éditeur de texte copier.

J'ai inclus tout le code ci-dessous. Le javascript en question est inclus dans les commentaires "Begin" et "End".

Merci pour votre aide, Tim

Structure du répertoire du plugin:

plugin-Shell > plugin-Shell.php
plugin-Shell > assets > js > admin > wordcount.js
plugin-Shell > assets > css > admin > style.css
plugin-Shell > assets > css > frontend > style.css

Feuille de style d'administration:

#after_editor-sortables {
    padding-top: 40px;
}
#wordcount {
    background-color: #fff;
    color: #000;
    border-color: #525252;
    border-style: solid;
    border-width: 5px;
    padding: 5px;
    width: 50px;
}

Javascript:

var i=0;
jQuery(document).ready(function($){
    setInterval(function(){
        var replacedTags = "";
        var replacedEntities = "";
        var tinymcevalue = "";

        console.log('Text: ' + tinymcevalue);
        console.log('Display: ' + $('textarea#content').css('display'));

        // BEGIN

        if($('textarea#content').css('display') == 'none'){ 
            tinymcevalue =    $('#content_ifr').contents().find('#tinymce').html(); 
        } else { 
            tinymcevalue = $('textarea#content').contents(); // Failed
         // tinymcevalue = $('textarea#content').html();     // Failed
        }

        // END

        var regexTags = /<[^>]+>/g;
        var regexEntities = /&lt;[\s\S]+?&gt;/gi;
        if (tinymcevalue !== "") {    
            replacedTags = tinymcevalue.replace(regexTags , "");
            replacedEntities = replacedTags.replace(regexEntities , "");
        }

        var wordscount = replacedEntities.split(" ");

        $("#wordcount").text(wordscount.length);
    }, 5000)
}); 

Plugin Shell:

<?php

/*
   Plugin Name: PluginShell
   Plugin URI: http://www.pluginshell.com/
   Description: Aenean Vestibulum Risus Commodo Ullamcorper
   Author: PluginShell
   Author URI: http://www.pluginshell.com/
   Version: 0.0.0
*/

mb_internal_encoding("UTF-8");
class Plugin_Shell {
   /**
    *
    * CONSTRUCTOR
    * Adds all actions and filters to the class
    *
    * @since 0.0.0
    *
    **/ 
    function __construct() {
        //Actions
        add_action( 'init',                  array( &$this, 'plugin_Shell_register_post_type'       ) );
        add_action( 'admin_init',            array( &$this, 'plugin_Shell_register_and_build_fields') );
        add_action( 'wp_enqueue_scripts',    array( &$this, 'plugin_Shell_enqueue_style'            ) );
        add_action( 'admin_enqueue_scripts', array( &$this, 'plugin_Shell_enqueue_wordcount_js'     ) );
        add_action( 'admin_enqueue_scripts', array( &$this, 'plugin_Shell_enqueue_options_style'    ) );
        add_action( 'admin_menu',            array( &$this, 'plugin_Shell_add_meta_boxes'           ) );
        add_action( 'admin_menu',            array( &$this, 'plugin_Shell_options_page'             ) );
        add_action( 'add_meta_boxes',        array( &$this, 'plugin_Shell_add_contextable_meta_box' ) );
        add_action( 'save_post',             array( &$this, 'plugin_Shell_meta_box_save' ), 1, 2      );
        add_action( 'edit_form_after_editor',array( &$this, 'add_after_editor_meta_boxes'           ) );
        add_action( 'edit_form_after_title', array( &$this, 'add_after_title_meta_boxes'            ) );

    }

   /**
    *
    * PHP4 CONSTRUCTOR
    * Calls __construct to create class
    *
    * @since 0.0.0
    *
    **/ 
    function plugin_Shell() {
        $this->__construct();
    }

   /**
    *
    * LOAD JS ONTO THE ADMIN PAGE
    *
    * @since 0.0.0
    *
    **/ 
    function plugin_Shell_enqueue_wordcount_js() {
        //die('BEGIN: plugin_Shell_enqueue_wordcount_js');
        wp_register_script( 'plugin-Shell-wordcount-js',  plugin_dir_url( __FILE__ ) . 'assets/js/admin/wordcount.js' );
        //die('MIDDLE: plugin_Shell_enqueue_wordcount_js');
        wp_enqueue_script( 'plugin-Shell-wordcount-js' ); 
        //die('END: plugin_Shell_enqueue_wordcount_js');
    }

   /**
    *
    * LOAD CSS INTO THE WEBSITE'S FRONT END
    *
    * @since 0.0.0
    *
    **/ 
    function plugin_Shell_enqueue_style() {
        wp_register_style( 'plugin-Shell-style',  plugin_dir_url( __FILE__ ) . 'assets/css/frontend/style.css' );
        wp_enqueue_style( 'plugin-Shell-style' ); 
    }

   /**
    *
    * LOAD CSS INTO THE ADMIN PAGE
    *
    * @since 0.0.0
    *
    **/ 
    function plugin_Shell_enqueue_options_style() {
        wp_register_style( 'plugin-Shell-options-style',  plugin_dir_url( __FILE__ ) . 'assets/css/admin/style.css' );
        wp_enqueue_style( 'plugin-Shell-options-style' ); 
    }

   /**
    * Register meta box context location: after_editor
    *
    * @return null
    **/
    function add_after_editor_meta_boxes() {
        global $post, $wp_meta_boxes;
        # Output the `after_editor` meta boxes:
        do_meta_boxes( get_current_screen(), 'after_editor', $post );
    }

   /**
    * Register meta box context location: after_title
    *
    * @return null
    **/
    function add_after_title_meta_boxes() {
        global $post, $wp_meta_boxes;
        # Output the `after_title` meta boxes:
        do_meta_boxes( get_current_screen(), 'after_title', $post );
    }

   /**
    *
    * REGISTER CUSTOM POST TYPE: plugin_Shell
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_register_post_type() {
        $options = get_option('plugin_Shell_options');

        register_post_type( 'plugin_Shell',
            array(
                'labels' => array(
                    'name' => __( 'Plugin Shell' ),
                    'singular_name' => __( 'term' ),
                    'add_new' => __( 'Add New' ),
                    'add_new_item' => __( 'Add New Term' ),
                    'edit' => __( 'Edit' ),
                    'edit_item' => __( 'Edit Term' ),
                    'new_item' => __( 'New Term' ),
                    'view' => __( 'View Term' ),
                    'view_item' => __( 'View Term' ),
                    'search_items' => __( 'Search Term' ),
                    'not_found' => __( 'No Terms found' ),
                    'not_found_in_trash' => __( 'No Terms found in Trash' )
                ),
                'public' => true,
                'query_var' => true,
                'show_in_menu' => true,
                'show_ui' => true,
                'menu_icon' => 'dashicons-book-alt',
                'supports' => array( 'title', 'editor' ),
                'rewrite' => array( 'slug' => $options['plugin_Shell_slug_url_setting'] ? get_post($options['plugin_Shell_slug_url_setting'])->post_name : 'plugin-Shell', 'with_front' => false )
            )
        );
    }

/*********************************************************
    BEGIN: CONTEXTABLE META BOX
 *********************************************************/

   /**
    *
    * CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE CONTEXTABLE PLUGIN Shell META BOX
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_add_contextable_meta_box() {
        $this->_plugin_Shell_add_contextable();
    }

   /**
    *
    * RENDERS THE META BOX 
    * Responsible for allowing the user to enter the plugin Shell term.
    *
    * @since 0.0.0
    *
    **/
    function _plugin_Shell_add_contextable() {
        add_meta_box( 
            'contextable-meta-box', 
            __( 'Extended Context Meta Box', 'pluginshell-textdomain' ), 
            array( &$this, '_display_contextable_meta_box' ), 
            'plugin_Shell', // CHANGE TO DESIRED post-type
            'after_editor', // CHANGE THIS TO 'after_editor' || 'after_title' || OR OTHER VALID CONTEXT LOCATION
            'default' 
        );
    }

   /**
    * 
    * DISPLAYS THE CONTENTS OF THE PLUGIN Shell TERM META BOX
    *
    * @since 0.0.0
    *
    **/ 
    function _display_contextable_meta_box() {

        printf( '<div id="wordcount"></div><br />&nbsp;<br />' );
    }

/*********************************************************
    END: CONTEXTABLE META BOX
 *********************************************************/

   /**
    * 
    * CALLS ALL OF THE FUNCTIONS RESPONSIBLE FOR RENDERING THE PLUGIN Shell META BOX
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_add_meta_boxes() {
        $this->_plugin_Shell_add_meta_box();
    }

   /**
    *
    * RENDERS THE META BOX 
    * Responsible for allowing the user to enter the plugin Shell term.
    *
    * @since 0.0.0
    *
    **/
    function _plugin_Shell_add_meta_box() {
        add_meta_box( 'plugin_Shell', __('Plugin Shell Extra Meta Box', 'pluginshell-textdomain'), array( &$this, '_plugin_Shell_definiton_meta_box' ), 'plugin_Shell', 'normal', 'high' );
    }

   /**
    * 
    * DISPLAYS THE CONTENTS OF THE PLUGIN Shell TERM META BOX
    *
    * @since 0.0.0
    *
    **/ 
    function _plugin_Shell_definiton_meta_box() {
        ?>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vitae elit libero, a pharetra augue. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Nullam id dolor id nibh ultricies vehicula ut id elit. Donec id elit non mi porta gravida at eget metus.</p>

<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Nullam quis risus eget urna mollis ornare vel eu leo. Vestibulum id ligula porta felis euismod semper. Curabitur blandit tempus porttitor. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.</p>

<p>Vestibulum id ligula porta felis euismod semper. Cras mattis consectetur purus sit amet fermentum. Vestibulum id ligula porta felis euismod semper. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
<?php
    }

   /**
    * 
    * SAVES PLUGIN Shell TERM
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_meta_box_save( $post_id, $post ) {
        $key = '_plugin_Shell_term';

        //  verify the nonce
        if ( !isset($_POST['_plugin_Shell_nonce']) || !wp_verify_nonce( $_POST['_plugin_Shell_nonce'], plugin_basename(__FILE__) ) )
            return;

        //  don't try to save the data under autosave, ajax, or future post.
        if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
        if ( defined('DOING_AJAX') && DOING_AJAX ) return;
        if ( defined('DOING_CRON') && DOING_CRON ) return;

        //  is the user allowed to edit the URL?
        if ( ! current_user_can( 'edit_posts' ) || $post->post_type != 'plugin_Shell' )
            return;

        $value = isset( $_POST[$key] ) ? $_POST[$key] : '';

        if ( $value ) {
            //  save/update
            $my_post = array();
            update_post_meta($post->ID, $key, $value);
        } else {
            //  delete if blank
            delete_post_meta($post->ID, $key);
        }

    }

   /**
    *
    * ADMIN MENU AND
    * SETTING FEILDS
    *
    **/

   /**
    * 
    * BUILD THE SETTINGS OPTIONS PAGE
    *
    * @since 0.0.0
    *
    **/
    function _plugin_Shell_build_options_page() { 
        ?>
        <div id="plugin-Shell-options-wrap">
            <div class="icon32" id="icon-tools"> <br /> </div>
            <form method="post" action="options.php" enctype="multipart/form-data">
                <?php settings_fields('plugin_Shell_option_group'); ?>
                <?php do_settings_sections(__FILE__); ?>
                <p class="submit">
                    <input name="Submit" type="submit" class="button-primary" value="<?php esc_attr_e('Save Changes'); ?>" />
                </p>
            </form>
            <p><hr></p>
            <p>* After editing the Slug the Permalinks Settings must be saved again.</p>
        </div>
        <?php 
    }

   /**
    * 
    * REGISTER SETTINGS AND FIELDS FOR OPTIONS PAGE
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_register_and_build_fields() {
        register_setting('plugin_Shell_option_group', 'plugin_Shell_option_mainpage', 'plugin_Shell_validate_setting');
        add_settings_section('plugin_Shell_settings_general', 'Plugin Shell General Settings', array( &$this, '_plugin_Shell_settings_fields'), __FILE__);
    }

   /**
    * 
    * RENDER THE SLUG SELECTION SETTINGS FIELD
    *
    * @since 0.9.2
    *
    **/
    function _plugin_Shell_settings_fields() {
        add_settings_field('slug', 'Mainpage:', array( &$this, '_plugin_Shell_slug_url_setting'), __FILE__, 'plugin_Shell_settings_general');
    } 

   /**
    * 
    * SANITIZE OPTIONS
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_validate_setting($plugin_Shell_options) {
        return $plugin_Shell_options;
    }


   /**
    * 
    * GET DROPDOWN OF ALL PAGES FOR SLUG SETTING OPTION
    *
    * @since 0.0.0
    *
    **/
    function _plugin_Shell_slug_url_setting() {
        $options = get_option('plugin_Shell_options');
        wp_dropdown_pages(array('name' => 'theme_options[plugin_Shell_slug_url_setting]', 'selected' => $options['plugin_Shell_slug_url_setting'] ));
    }

   /**
    * 
    * ADD THE OPTIONS PAGE
    *
    * @since 0.0.0
    *
    **/
    function plugin_Shell_options_page() { 
        add_options_page('Plugin Shell', 'Plugin Shell', 'administrator', __FILE__, array( &$this, '_plugin_Shell_build_options_page' ) );
    }
};

/**
 * 
 * INSTANTIATE CLASS plugin_Shell
 *
 * @since 0.0.0
 *
 **/
$PluginShell = new plugin_Shell;

?>
1
mpactMEDIA

L'éditeur TinyMCE a des fonctions dans son API pour obtenir le contenu de l'éditeur. Pour obtenir tout le contenu de la sélection, utilisez la source suivante:

tinyMCE.activeEditor.selection.getContent();

WordPress a depuis 4.3 beaucoup de changements dans l'éditeur. Utilisez toujours l’API 4 pour trouver les bonnes fonctions dans la page de documentation. Ici pour la documentation sur l'obtention de contenu dans l'éditeur. Toutes les fonctions utiles de l'API vous trouvent dans ce lien ci-dessous.

Pour obtenir tout le contenu, utilisez tinymce.activeEditor.selection.getNode().

Pour l'utilisation dans l'environnement WordPress, vous pouvez également utiliser jQuery, est une partie du noyau. Comme exemple, créez une instance de tinymce et ajoutez votre source.

jQuery( document ).ready( function( $ ) {

    tinymce.PluginManager.add( 'Your_Namespace', function( editor ) {

                if ( typeof(
                        tinymce.activeEditor.selection.getContent()
                    ) != 'undefined' ) {
                    marked = true;
                }

                if ( marked == true ) {
                    var content       = tinymce.activeEditor.selection.getContent(),
                        start_content = tinymce.activeEditor.selection.getStart().nodeName,
                        all           = tinymce.activeEditor.selection.getNode()
                }

                // Debug in Console
                console.log(all);

    } );
} );
1
bueltge