这是分类术语列表插件到小部件的简单转换:
class WPSE_5394_Widget extends WP_Widget
{
public function __construct()
{
parent::__construct( \'wpse5394_widget\', \'Taxonomy Terms List\' );
}
public function widget( $sidebar_args, $widget_options )
{
if ( ! is_single() ) {
// I don\'t think we can display anything sensible on a page with multiple posts
return;
}
$output = $sidebar_args[\'before_widget\'];
// If we want to use this we should provide a way to set the title
if ( ! empty( $widget_options[\'title\'] ) ) {
$output = $sidebar_args[\'before_title\'] . $widget_options[\'title\'] . $sidebar_args[\'after_title\'];
}
// This is the meat of the function: get the taxonomies we want to display, and get the terms for each taxonomy
$taxonomy_names = apply_filters( \'wpse5394_taxonomies\', array_fill_keys( get_taxonomies(), true ) );
$taxonomy_terms = \'\';
foreach ( $taxonomy_names as $taxonomy_name => $dummy ) {
$taxonomy = get_taxonomy( $taxonomy_name );
$before = apply_filters( \'wpse5394_taxonomy_before\', \'<p>\' . $taxonomy->label . \': \', $taxonomy );
$sep = apply_filters( \'wpse5394_taxonomy_sep\', \', \' );
$after = apply_filters( \'wpse5394_taxonomy_after\', \'</p>\' );
$terms = get_the_term_list( 0, $taxonomy_name, $before, $sep, $after );
if ( $terms ) {
$taxonomy_terms .= $terms;
}
}
if ( ! $taxonomy_terms ) {
// No taxonomy terms will be displayed - don\'t display the widget
return;
}
$output .= $taxonomy_terms;
$output .= $sidebar_args[\'after_widget\'];
echo $output;
}
}
add_action( \'widgets_init\', \'wpse5394_widgets_init\' );
function wpse5394_widgets_init()
{
register_widget( \'WPSE_5394_Widget\' );
}
大多数选项都可以通过过滤器设置,如要显示的分类:
add_filter( \'wpse5394_taxonomies\', \'wpse5394_taxonomies\' );
function wpse5394_taxonomies( $taxonomies )
{
unset( $taxonomies[\'category\'] );
return $taxonomies;
}