web-dev-qa-db-fra.com

Ajout d'un champ Colorpicker à la catégorie

Je souhaite ajouter à mes catégories un champ personnalisé dans lequel l'utilisateur peut les colorier. J'ai ajouté le champ, mais je souhaite utiliser colorpicker (minuscule ou farbtastic) pour permettre à l'utilisateur de choisir facilement les couleurs. Je ne sais pas encore comment ajouter la fonctionnalité, voici ce que j'ai jusqu'à présent:

Catégorie Configuration sur le terrain

/** Add New Field To Category **/
function extra_category_fields( $tag ) {
    $t_id = $tag->term_id;
    $cat_meta = get_option( "category_$t_id");
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="cat_Image_url"><?php _e('Category Image Url'); ?></label></th>
<td>
<input type="text" name="Cat_meta[bgc]" id="colorinput" size="3" style="width:20%;" value="<?php echo $cat_meta['bgc'] ? $cat_meta['bgc'] : '#fff'; ?>" class="my-color-field" />
<div id="colorpicker"></div><br />
            <span class="description"><?php _e('Can't Think of A Desc Yet, Suggestions?'); ?></span>
                <br />
        </td>
</tr>
<?php
}
add_action ( 'category_add_form_fields', 'extra_category_fields');

/** Save Category Meta **/
function save_extra_category_fileds( $term_id ) {
    if ( isset( $_POST['Cat_meta'] ) ) {
        $t_id = $term_id;
        $cat_meta = get_option( "category_$t_id");
        $cat_keys = array_keys($_POST['Cat_meta']);
            foreach ($cat_keys as $key){
            if (isset($_POST['Cat_meta'][$key])){
                $cat_meta[$key] = $_POST['Cat_meta'][$key];
            }
        }
        //save the option array
        update_option( "category_$t_id", $cat_meta );
    }
}
add_action ( 'edited_category', 'save_extra_category_fileds');

Script Colorpicker (Farbtastic) - Ne fonctionne pas

/** Enqueue Color Picker **/
function farbtastic_scripts() {
  wp_enqueue_script( 'jQuery' );
  wp_enqueue_style( 'farbtastic' );
  wp_enqueue_script( 'farbtastic' );

  ?>
    <script type="text/javascript">

        jQuery(document).ready(function() {
            jQuery('#colorpicker').hide();
            jQuery('#colorpicker').farbtastic("#colorinput");
            jQuery("#colorinput").click(function(){jQuery('#colorpicker').slideToggle()});
        });

    </script>
  <?php
}
add_action( 'admin_enqueue_scripts', 'farbtastic_scripts' );

:: Edit :: Si cela facilite les choses, j’ai le plug-in "Advanced Custom Fields" qui a une option colorpicker. Je cherche à voir s'il serait plus facile de l'utiliser.

4
Howdy_McGee

Ceci a été mis à jour pour WordPress 4+ avec l'introduction de Term Meta. Le code est fortement commenté.

:: Mes fonctions - functions.php ::

La fonction ci-dessous consiste à afficher le sélecteur de couleurs sur l'écran "Ajouter une nouvelle catégorie":

/**
 * Add new colorpicker field to "Add new Category" screen
 * - https://developer.wordpress.org/reference/hooks/taxonomy_add_form_fields/
 *
 * @param String $taxonomy
 *
 * @return void
 */
function colorpicker_field_add_new_category( $taxonomy ) {

  ?>

    <div class="form-field term-colorpicker-wrap">
        <label for="term-colorpicker">Category Color</label>
        <input name="_category_color" value="#ffffff" class="colorpicker" id="term-colorpicker" />
        <p>This is the field description where you can tell the user how the color is used in the theme.</p>
    </div>

  <?php

}
add_action( 'category_add_form_fields', 'colorpicker_field_add_new_category' );  // Variable Hook Name

La fonction ci-dessous ajoutera le champ colorpicker à l'écran "Edit Category":

/**
 * Add new colopicker field to "Edit Category" screen
 * - https://developer.wordpress.org/reference/hooks/taxonomy_add_form_fields/
 *
 * @param WP_Term_Object $term
 *
 * @return void
 */
function colorpicker_field_edit_category( $term ) {

    $color = get_term_meta( $term->term_id, '_category_color', true );
    $color = ( ! empty( $color ) ) ? "#{$color}" : '#ffffff';

  ?>

    <tr class="form-field term-colorpicker-wrap">
        <th scope="row"><label for="term-colorpicker">Severity Color</label></th>
        <td>
            <input name="_category_color" value="<?php echo $color; ?>" class="colorpicker" id="term-colorpicker" />
            <p class="description">This is the field description where you can tell the user how the color is used in the theme.</p>
        </td>
    </tr>

  <?php


}
add_action( 'category_edit_form_fields', 'colorpicker_field_edit_category' );   // Variable Hook Name

La fonction ci-dessous désinfectera et sauvegardera le terme méta sans le #, mais il existe une fonction distincte qui le désinfectera avec le hachage appelé sanitize_hex_color() :

/**
 * Term Metadata - Save Created and Edited Term Metadata
 * - https://developer.wordpress.org/reference/hooks/created_taxonomy/
 * - https://developer.wordpress.org/reference/hooks/edited_taxonomy/
 *
 * @param Integer $term_id
 *
 * @return void
 */
function save_termmeta( $term_id ) {

    // Save term color if possible
    if( isset( $_POST['_category_color'] ) && ! empty( $_POST['_category_color'] ) ) {
        update_term_meta( $term_id, '_category_color', sanitize_hex_color_no_hash( $_POST['_category_color'] ) );
    } else {
        delete_term_meta( $term_id, '_category_color' );
    }

}
add_action( 'created_category', 'save_termmeta' );  // Variable Hook Name
add_action( 'edited_category',  'save_termmeta' );  // Variable Hook Name

Maintenant que les champs sont ajoutés et que les données sont en cours de sauvegarde, nous devons mettre en file d'attente le ou les scripts qui ont mis le sélecteur de couleurs en place. Notez que dans la première condition, je teste par rapport à la taxonomie sur laquelle je montre le champ.

/**
 * Enqueue colorpicker styles and scripts.
 * - https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
 *
 * @return void
 */
function category_colorpicker_enqueue( $taxonomy ) {

    if( null !== ( $screen = get_current_screen() ) && 'edit-category' !== $screen->id ) {
        return;
    }

    // Colorpicker Scripts
    wp_enqueue_script( 'wp-color-picker' );

    // Colorpicker Styles
    wp_enqueue_style( 'wp-color-picker' );

}
add_action( 'admin_enqueue_scripts', 'category_colorpicker_enqueue' );

Enfin, nous devons initialiser le Colorpicker. Ici, j’ai choisi de simplement l’imprimer dans le pied de page, mais il peut être plus avantageux, notamment du point de vue des plugins, de le placer dans un fichier externe et de le mettre en file d’attente comme un script normal.

/**
 * Print javascript to initialize the colorpicker
 * - https://developer.wordpress.org/reference/hooks/admin_print_scripts/
 *
 * @return void
 */
function colorpicker_init_inline() {

    if( null !== ( $screen = get_current_screen() ) && 'edit-category' !== $screen->id ) {
        return;
    }

  ?>

    <script>
        jQuery( document ).ready( function( $ ) {

            $( '.colorpicker' ).wpColorPicker();

        } ); // End Document Ready JQuery
    </script>

  <?php

}
add_action( 'admin_print_scripts', 'colorpicker_init_inline', 20 );
4
Howdy_McGee