Come utilizzare le tassonomie sugli allegati con la nuova Libreria Media?
WordPress 3.5 ha modificato la gestione dei media e ora la schermata di modifica della Libreria Media utilizza l'interfaccia UI predefinita dei post type. Le tassonomie sono molto utili per installazioni WP con diversi utenti e allegati, offrendo più possibilità per trovare l'allegato e/o aggiungere classificazioni.
Ho visto Posso aggiungere un metabox Categoria agli allegati? su WPSE, ma non è perfetto da usare con WP 3.5 e inoltre non ha informazioni sull'uso di categorie personalizzate sugli allegati, non solo le categorie dei post.
In breve: è possibile aggiungere categorie/tag personalizzati agli allegati da utilizzare nella Libreria Media con WP 3.5?

Per aggiungere le tassonomie dal post type predefinito 'post', è semplice aggiungere le tassonomie 'category' e 'tags' con un piccolo plugin come il sorgente qui sotto.
<?php
/**
* Plugin Name: Attachment Taxonomies
* Plugin URI:
* Text Domain: attachment_taxonomies
* Domain Path: /languages
* Description:
* Version: 1.0.0
* Author: Frank Bültge
* Author URI: http://bueltge.de
* License: GPLv3
*/
add_action( 'init', 'fb_attachment_taxonomies' );
function fb_attachment_taxonomies() {
$taxonomies = array( 'category', 'post_tag' ); // aggiunge le 2 tassonomie a ...
foreach ( $taxonomies as $tax ) {
register_taxonomy_for_object_type( $tax, 'attachment' ); // aggiunge al post type attachment
}
}
Per utilizzare tassonomie personalizzate sugli allegati è importante creare una tassonomia personalizzata e assegnarla al post type attachment
, come nel seguente plugin.
<?php
/**
* Plugin Name: Attachment Taxonomies
* Plugin URI:
* Text Domain: attachment_taxonomies
* Domain Path: /languages
* Description:
* Version: 1.0.0
* Author: Frank Bültge
* Author URI: http://bueltge.de
* License: GPLv3
*/
if ( function_exists( 'add_filter' ) )
add_action( 'plugins_loaded', array( 'Fb_Attachment_Taxonomies', 'get_object' ) );
/**
* Aggiunge le tassonomie Tags e Categories agli Allegati con WP 3.5
*/
class Fb_Attachment_Taxonomies {
static private $classobj;
/**
* Costruttore, inizializza le funzioni all'interno di WP
*
* @since 1.0.0
* @return void
*/
public function __construct() {
// carica i file di traduzione
add_action( 'admin_init', array( $this, 'localize_plugin' ) );
// aggiunge le tassonomie
add_action( 'init', array( $this, 'setup_taxonomies' ) );
}
/**
* Gestore per l'azione 'init'. Istanzia questa classe.
*
* @since 1.0.0
* @access public
* @return $classobj
*/
public function get_object() {
if ( NULL === self::$classobj ) {
self::$classobj = new self;
}
return self::$classobj;
}
/**
* Funzione per localizzare il plugin.
*
* @uses load_plugin_textdomain, plugin_basename
* @since 2.0.0
* @return void
*/
public function localize_plugin() {
load_plugin_textdomain(
'attachment_taxonomies',
FALSE,
dirname( plugin_basename( __FILE__ ) ) . '/languages/'
);
}
/**
* Configura le Tassonomie
* Crea le tassonomie 'attachment_tag' e 'attachment_category'.
* Migliorabile tramite il filtro `fb_attachment_taxonomies`
*
* @uses register_taxonomy, apply_filters
* @since 1.0.0
* @return void
*/
public function setup_taxonomies() {
$attachment_taxonomies = array();
// Tags
$labels = array(
'name' => _x( 'Tag Media', 'nome generale della tassonomia', 'attachment_taxonomies' ),
'singular_name' => _x( 'Tag Media', 'nome singolare della tassonomia', 'attachment_taxonomies' ),
'search_items' => __( 'Cerca Tag Media', 'attachment_taxonomies' ),
'all_items' => __( 'Tutti i Tag Media', 'attachment_taxonomies' ),
'parent_item' => __( 'Tag Media Genitore', 'attachment_taxonomies' ),
'parent_item_colon' => __( 'Tag Media Genitore:', 'attachment_taxonomies' ),
'edit_item' => __( 'Modifica Tag Media', 'attachment_taxonomies' ),
'update_item' => __( 'Aggiorna Tag Media', 'attachment_taxonomies' ),
'add_new_item' => __( 'Aggiungi Nuovo Tag Media', 'attachment_taxonomies' ),
'new_item_name' => __( 'Nome Nuovo Tag Media', 'attachment_taxonomies' ),
'menu_name' => __( 'Tag Media', 'attachment_taxonomies' ),
);
$args = array(
'hierarchical' => FALSE,
'labels' => $labels,
'show_ui' => TRUE,
'show_admin_column' => TRUE,
'query_var' => TRUE,
'rewrite' => TRUE,
);
$attachment_taxonomies[] = array(
'taxonomy' => 'attachment_tag',
'post_type' => 'attachment',
'args' => $args
);
// Categories
$labels = array(
'name' => _x( 'Categorie Media', 'nome generale della tassonomia', 'attachment_taxonomies' ),
'singular_name' => _x( 'Categoria Media', 'nome singolare della tassonomia', 'attachment_taxonomies' ),
'search_items' => __( 'Cerca Categorie Media', 'attachment_taxonomies' ),
'all_items' => __( 'Tutte le Categorie Media', 'attachment_taxonomies' ),
'parent_item' => __( 'Categoria Media Genitore', 'attachment_taxonomies' ),
'parent_item_colon' => __( 'Categoria Media Genitore:', 'attachment_taxonomies' ),
'edit_item' => __( 'Modifica Categoria Media', 'attachment_taxonomies' ),
'update_item' => __( 'Aggiorna Categoria Media', 'attachment_taxonomies' ),
'add_new_item' => __( 'Aggiungi Nuova Categoria Media', 'attachment_taxonomies' ),
'new_item_name' => __( 'Nome Nuova Categoria Media', 'attachment_taxonomies' ),
'menu_name' => __( 'Categorie Media', 'attachment_taxonomies' ),
);
$args = array(
'hierarchical' => TRUE,
'labels' => $labels,
'show_ui' => TRUE,
'query_var' => TRUE,
'rewrite' => TRUE,
);
$attachment_taxonomies[] = array(
'taxonomy' => 'attachment_category',
'post_type' => 'attachment',
'args' => $args
);
$attachment_taxonomies = apply_filters( 'fb_attachment_taxonomies', $attachment_taxonomies );
foreach ( $attachment_taxonomies as $attachment_taxonomy ) {
register_taxonomy(
$attachment_taxonomy['taxonomy'],
$attachment_taxonomy['post_type'],
$attachment_taxonomy['args']
);
}
}
} // fine classe
Vedi il risultato nello screenshot seguente, anche la differenza - più semplice delle mie poche parole sul sorgente. Ma l'immagine della mia persona nell'esempio dello screenshot non è rilevante per il sorgente ;)
Piccoli suggerimenti: l'interfaccia utente dalla finestra modale per aggiungere media sul post type è leggermente diversa rispetto alla schermata di modifica sul post type attachment. Le tassonomie gerarchiche hanno solo un albero nella schermata di modifica. Nella finestra modale è un campo di input e la tassonomia funziona con la virgola come separatore. Vedi anche questo post di Helen sul blog di WP Core. Ma vedi anche le tassonomie personalizzate per 'tags' e 'categories' in uno screenshot.

+1+ Un altro passo nella scoperta della Media Library 3.5, la grande sconosciuta del 2012!

Sì, hai ragione. Mi piace questo parametro in WP 3.6; lo uso spesso con una piccola classe helper, quando utilizzo molte tassonomie: https://github.com/bueltge/WP-Control-Taxonomy

Frank, non dimenticare che per le tassonomie degli allegati, dovresti probabilmente impostare update_count_callback
su _update_generic_term_count
. Vedi la voce aggiornata del Codex per il motivo: http://codex.wordpress.org/Function_Reference/register_taxonomy#Arguments

Estenderò la risposta di Frank con Aggiunta di un Filtro per Tassonomia alla Lista Admin per un Custom Post Type?
Cercando entrambe le cose, Categorie Media e Filtro per Tassonomia, ho unito il codice di Frank con la risposta di Kaiser in quel post. Ho anche aggiunto un tocco personale per includere il post type, dove l'allegato è stato caricato, come Categoria.
Risulta in questo:
add_action(
'plugins_loaded',
array ( WPSE76720_Attachment_Taxonomies::get_object(), 'plugin_setup' )
);
// BUELTGE/KAISER/RUDOLF
class WPSE76720_Attachment_Taxonomies
{
protected static $instance = NULL;
public $post_type;
public $taxonomies;
/**
* Utilizzato per il normale funzionamento del plugin.
*
* @wp-hook plugins_loaded
* @return void
*/
public function plugin_setup()
{
// Filtro per tassonomie
add_action( 'load-upload.php', array( $this, 'setup' ) );
// aggiungi tassonomie
add_action( 'init', array( $this, 'setup_taxonomies' ) );
add_action( 'add_attachment', array( $this, 'auto_tax' ), 10, 2 );
}
/**
* Costruttore, inizializza le funzioni all'interno di WP
*
* @since 1.0.0
* @return void
*/
public function __construct() {}
/**
* Gestore per l'azione 'init'. Istanzia questa classe.
*
* @since 1.0.0
* @access public
* @return $instance
*/
public function get_object()
{
NULL === self::$instance and self::$instance = new self;
return self::$instance;
}
/**
* Configura le Tassonomie
* Crea le tassonomie 'attachment_tag' e 'attachment_category'.
* Migliorabile tramite filtro `fb_attachment_taxonomies`
*
* @uses register_taxonomy, apply_filters
* @since 1.0.0
* @return void
*/
public function setup_taxonomies()
{
$attachment_taxonomies = array();
// Categorie
$labels = array(
'name' => __( 'Categorie Media', 'b5f-mc' ),
'singular_name' => __( 'Categoria Media', 'b5f-mc' ),
'search_items' => __( 'Cerca Categorie Media', 'b5f-mc' ),
'all_items' => __( 'Tutte le Categorie Media', 'b5f-mc' ),
'parent_item' => __( 'Categoria Media Genitore', 'b5f-mc' ),
'parent_item_colon' => __( 'Categoria Media Genitore:', 'b5f-mc' ),
'edit_item' => __( 'Modifica Categoria Media', 'b5f-mc' ),
'update_item' => __( 'Aggiorna Categoria Media', 'b5f-mc' ),
'add_new_item' => __( 'Aggiungi Nuova Categoria Media', 'b5f-mc' ),
'new_item_name' => __( 'Nome Nuova Categoria Media', 'b5f-mc' ),
'menu_name' => __( 'Categorie Media', 'b5f-mc' ),
);
$args = array(
'hierarchical' => TRUE,
'labels' => $labels,
'show_admin_column' => TRUE,
'show_ui' => TRUE,
'query_var' => TRUE,
'rewrite' => TRUE,
);
$attachment_taxonomies[] = array(
'taxonomy' => 'attachment_category',
'post_type' => 'attachment',
'args' => $args
);
$attachment_taxonomies = apply_filters( 'fb_attachment_taxonomies', $attachment_taxonomies );
foreach ( $attachment_taxonomies as $attachment_taxonomy ) {
register_taxonomy(
$attachment_taxonomy['taxonomy'],
$attachment_taxonomy['post_type'],
$attachment_taxonomy['args']
);
}
}
public function setup()
{
add_action( current_filter(), array( $this, 'setup_vars' ), 20 );
add_action( 'restrict_manage_posts', array( $this, 'get_select' ) );
add_filter( "manage_taxonomies_for_attachment_columns", array( $this, 'add_columns' ) );
}
public function setup_vars()
{
$this->post_type = 'attachment';
$this->taxonomies = get_object_taxonomies( $this->post_type );
}
public function add_columns( $taxonomies )
{
return array_merge(
$taxonomies
,$this->taxonomies
);
}
public function get_select()
{
$walker = new WCMF_walker;
foreach ( $this->taxonomies as $tax )
{
wp_dropdown_categories( array(
'taxonomy' => $tax
,'hide_if_empty' => false
,'show_option_all' => sprintf(
get_taxonomy( $tax )->labels->all_items
)
,'hide_empty' => false
,'hierarchical' => is_taxonomy_hierarchical( $tax )
,'show_count' => false
,'orderby' => 'name'
,'selected' => '0' !== get_query_var( $tax )
? get_query_var( $tax )
: false
,'name' => $tax
,'id' => $tax
,'walker' => $walker
) );
}
}
/**
* Aggiunge il post type genitore come categoria dell'allegato
*
* @author Rodolfo Buaiz
*/
public function auto_tax( $post_id )
{
$the_p = get_post( $post_id );
if( $the_p->post_parent > 0 )
{
$cpt = get_post_type( $the_p->post_parent );
$term = term_exists( $cpt, 'attachment_category' );
if( !$term )
$term = wp_insert_term( $cpt, 'attachment_category' );
wp_set_post_terms( $post_id, $term['term_id'], 'attachment_category', true );
}
}
} // fine BUELTGE/KAISER/RUDOLF
// KAISER
class WCMF_walker extends Walker_CategoryDropdown
{
var $tree_type = 'category';
var $db_fields = array(
'parent' => 'parent'
,'id' => 'term_id'
);
public $tax_name;
/**
* @see Walker::start_el()
* @param string $output Passato per riferimento. Usato per aggiungere contenuto aggiuntivo.
* @param object $term Oggetto dati del termine di tassonomia.
* @param int $depth Profondità della categoria. Usato per il padding.
* @param array $args Usa le chiavi 'selected' e 'show_count', se esistono.
* @param int $id
* @return void
*/
function start_el( &$output, $term, $depth, $args, $id = 0 )
{
$pad = str_repeat( ' ', $depth * 3 );
$cat_name = apply_filters( 'list_cats', $term->name, $term );
$output .= sprintf(
'<option class="level-%s" value="%s" %s>%s%s</option>'
,$depth
,$term->slug
,selected(
$args['selected']
,$term->slug
,false
)
,"{$pad}{$cat_name}"
,$args['show_count']
? " ({$term->count})"
: ''
);
}
}
// fine KAISER

Il mio plugin Media Categories fa esattamente questo per te - inoltre ripulisce l'interfaccia nella Modal Media in modo da ottenere ancora la lista di checkbox, mentre normalmente si ottengono solo campi di testo.
