¿Agregar campos a la categoría, etiqueta y pantalla de edición de taxonomía personalizada en el administrador de WordPress?

32

La pregunta es " ¿Cómo agrego uno o más campos a la Categoría, Etiqueta y Edición de Taxonomía Personalizada en el Administrador de WordPress? " Esta pregunta era preguntado en la lista de wp-hackers 1 de agosto de 2010 y Ofrecí una solución más tarde ese día. El autor de la pregunta original volvió a hablar del tema hoy (21 de agosto), que me recordó la solución. Como podría ser una necesidad común, decidí publicar la solución, incluido el código aquí para que otros puedan encontrarlo en el futuro.

    
pregunta MikeSchinkel 22.08.2010 - 06:46

7 respuestas

21

Agregué el nuevo campo 'imagen' (archivo de tipo de entrada) a la categoría con la ayuda de estos

add_action('category_edit_form_fields','category_edit_form_fields');
add_action('category_edit_form', 'category_edit_form');
add_action('category_add_form_fields','category_edit_form_fields');
add_action('category_add_form','category_edit_form');


function category_edit_form() {
?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#edittag').attr( "enctype", "multipart/form-data" ).attr( "encoding", "multipart/form-data" );
        });
</script>
<?php 
}

function category_edit_form_fields () {
?>
    <tr class="form-field">
            <th valign="top" scope="row">
                <label for="catpic"><?php _e('Picture of the category', ''); ?></label>
            </th>
            <td>
                <input type="file" id="catpic" name="catpic"/>
            </td>
        </tr>
        <?php 
    }

Usted es libre de usar cualquier taxonomía, simplemente reemplace category a su nombre de taxonomía

    
respondido por el tpoxa 19.01.2011 - 12:26
7

Además, si desea agregar ese campo en el formulario de taxonomía personalizado, simplemente sustituya la categoría con el nombre de taxonomía personalizada en la función add_action .

Ejemplo:

add_action('{custom_taxonomy}_edit_form_fields','category_edit_form_fields');
add_action('{custom_taxonomy}_edit_form', 'category_edit_form');
add_action('{custom_taxonomy}_add_form_fields','category_edit_form_fields');
add_action('{custom_taxonomy}_add_form','category_edit_form');
    
respondido por el Ted 26.10.2011 - 03:53
2

Para aquellos que buscan enganchar en el campo de formulario de etiqueta, el enganche es ligeramente diferente.

add_tag_form_fields

en lugar de tag_add_form_fields como cabría esperar

    
respondido por el Dean_Wilson 28.09.2013 - 00:03
1

Me doy cuenta de que esto se solicitó hace un tiempo, pero WordPress ha cambiado un poco desde entonces, así que decidí desarrollar un pequeño script que simplifique el proceso de agregar campos personalizados a las taxonomías y, opcionalmente, le permite agregar columnas a la tabla de términos para cada campo. La secuencia de comandos se llama amarkal-taxonomy y es parte de Amarkal marco de WordPress.

Al utilizar amarkal-taxonomy , agregar un campo personalizado se simplifica a:

// Add a text field to the 'category' taxonomy 'add' & 'edit' forms:
amarkal_taxonomy_add_field('category', 'cat_icon', array(
    'type'        => 'text',
    'label'       => 'Icon',
    'description' => 'The category\'s icon',
    'table'       => array(
        'show'      => true,  // Add a column to the terms table
        'sortable'  => true   // Make that column sortable
    )
));

// Then you can retrieve the data using:
$icon = get_term_meta( $term_id, 'cat_icon', true );
    
respondido por el Yoav Kadosh 22.03.2017 - 16:41
1

Agregué la imagen Agregar y Eliminar imagen extra archivada en una taxonomía personalizada cuyo nombre es seguro.

/**
 * Plugin class
 **/
if ( ! class_exists( 'CT_TAX_META' ) ) {

class CT_TAX_META {

  public function __construct() {
    //
  }

 /*
  * Initialize the class and start calling our hooks and filters
  * @since 1.0.0
 */
 public function init() {
   add_action( 'insurance_add_form_fields', array ( $this, 'add_category_image' ), 10, 2 );
   add_action( 'created_insurance', array ( $this, 'save_category_image' ), 10, 2 );
   add_action( 'insurance_edit_form_fields', array ( $this, 'update_category_image' ), 10, 2 );
   add_action( 'edited_insurance', array ( $this, 'updated_category_image' ), 10, 2 );
   add_action( 'admin_enqueue_scripts', array( $this, 'load_media' ) );
   add_action( 'admin_footer', array ( $this, 'add_script' ) );
 }

public function load_media() {
 wp_enqueue_media();
}

 /*
  * Add a form field in the new category page
  * @since 1.0.0
 */
 public function add_category_image ( $taxonomy ) { ?>
   <div class="form-field term-group">
     <label for="category-image-id"><?php _e('Image', 'hero-theme'); ?></label>
     <input type="hidden" id="category-image-id" name="category-image-id" class="custom_media_url" value="">
     <div id="category-image-wrapper"></div>
     <p>
       <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
       <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
    </p>
   </div>
 <?php
 }

 /*
  * Save the form field
  * @since 1.0.0
 */
 public function save_category_image ( $term_id, $tt_id ) {
   if( isset( $_POST['category-image-id'] ) && '' !== $_POST['category-image-id'] ){
     $image = $_POST['category-image-id'];
     add_term_meta( $term_id, 'category-image-id', $image, true );
   }
 }

 /*
  * Edit the form field
  * @since 1.0.0
 */
 public function update_category_image ( $term, $taxonomy ) { ?>
   <tr class="form-field term-group-wrap">
     <th scope="row">
       <label for="category-image-id"><?php _e( 'Image', 'hero-theme' ); ?></label>
     </th>
     <td>
       <?php $image_id = get_term_meta ( $term -> term_id, 'category-image-id', true ); ?>
       <input type="hidden" id="category-image-id" name="category-image-id" value="<?php echo $image_id; ?>">
       <div id="category-image-wrapper">
         <?php if ( $image_id ) { ?>
           <?php echo wp_get_attachment_image ( $image_id, 'thumbnail' ); ?>
         <?php } ?>
       </div>
       <p>
         <input type="button" class="button button-secondary ct_tax_media_button" id="ct_tax_media_button" name="ct_tax_media_button" value="<?php _e( 'Add Image', 'hero-theme' ); ?>" />
         <input type="button" class="button button-secondary ct_tax_media_remove" id="ct_tax_media_remove" name="ct_tax_media_remove" value="<?php _e( 'Remove Image', 'hero-theme' ); ?>" />
       </p>
     </td>
   </tr>
 <?php
 }

/*
 * Update the form field value
 * @since 1.0.0
 */
 public function updated_category_image ( $term_id, $tt_id ) {
   if( isset( $_POST['category-image-id'] ) && '' !== $_POST['category-image-id'] ){
     $image = $_POST['category-image-id'];
     update_term_meta ( $term_id, 'category-image-id', $image );
   } else {
     update_term_meta ( $term_id, 'category-image-id', '' );
   }
 }

/*
 * Add script
 * @since 1.0.0
 */
 public function add_script() { ?>
   <script>
     jQuery(document).ready( function($) {
       function ct_media_upload(button_class) {
         var _custom_media = true,
         _orig_send_attachment = wp.media.editor.send.attachment;
         $('body').on('click', button_class, function(e) {
           var button_id = '#'+$(this).attr('id');
           var send_attachment_bkp = wp.media.editor.send.attachment;
           var button = $(button_id);
           _custom_media = true;
           wp.media.editor.send.attachment = function(props, attachment){
             if ( _custom_media ) {
               $('#category-image-id').val(attachment.id);
               $('#category-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
               $('#category-image-wrapper .custom_media_image').attr('src',attachment.url).css('display','block');
             } else {
               return _orig_send_attachment.apply( button_id, [props, attachment] );
             }
            }
         wp.media.editor.open(button);
         return false;
       });
     }
     ct_media_upload('.ct_tax_media_button.button'); 
     $('body').on('click','.ct_tax_media_remove',function(){
       $('#category-image-id').val('');
       $('#category-image-wrapper').html('<img class="custom_media_image" src="" style="margin:0;padding:0;max-height:100px;float:none;" />');
     });
     // Thanks: http://stackoverflow.com/questions/15281995/wordpress-create-category-ajax-response
     $(document).ajaxComplete(function(event, xhr, settings) {
       var queryStringArr = settings.data.split('&');
       if( $.inArray('action=add-tag', queryStringArr) !== -1 ){
         var xml = xhr.responseXML;
         $response = $(xml).find('term_id').text();
         if($response!=""){
           // Clear the thumb image
           $('#category-image-wrapper').html('');
         }
       }
     });
   });
 </script>
 <?php }

  }

$CT_TAX_META = new CT_TAX_META();
$CT_TAX_META -> init();

}

Nota: si desea agregar este campo a una taxonomía diferente, por ejemplo, para un tipo de publicación personalizada, deberías reemplazar la referencia a la categoría con una referencia a tu propia taxonomía. Por ejemplo, si agrega una taxonomía de género, podría enganchar esta función a través de

add_action( 'taxonomy_add_form_fields', array ( $this, 'add_category_image' ), 10, 2 ).

El nombre de mi taxonomía es seguro.

add_action ('insurance_add_form_fields', array ($ this, 'add_category_image'), 10, 2);

Use este código en su archivo functions.php .

    
respondido por el Vivekpathak 14.03.2018 - 13:33
0

Debe agregar su código a su archivo de funciones themes.php de temas - también si desea agregar ese campo al formulario de taxonomía personalizado, simplemente sustituya la categoría con el nombre de taxonomía personalizada en la función add_action. Ejemplo: add_action ('category_edit_form_fields', 'category_edit_form_fields'); estarán add_action ('custom_taxonomy_name_form_fields', 'function_name_to_hook_on');

    
respondido por el user3693 04.03.2011 - 07:02
0

Utilizo la Categoría Meta PLugin . Funciona en todas las taxonomías personalizadas, etiquetas y amp; categorías

    
respondido por el Blackbird 05.02.2012 - 15:25

Lea otras preguntas en las etiquetas