这里现有的答案很好,但不幸的是,由于答案的年龄,它不适用于WordPress的新版本。
下面的代码有两种改进:
1-这是WordPress新版本的推荐/最佳实践方法,自version 2.8
2-它允许您通过仪表板小部件界面选择分类法,而不是硬编码。
add_action( \'widgets_init\', \'custom_register_plugin_widget\' );
function custom_register_plugin_widget() {
register_widget( \'Widget_Custom_Tax_Tag_Cloud\' );
}
/**
* New "best practice" is to extend the built-in WP_Widget class
*
* Class Widget_Custom_tax_tag_cloud
*/
class Widget_Custom_Tax_Tag_Cloud extends WP_Widget {
function __construct() {
parent::__construct( \'custom_tax_tag_cloud\', \'Custom Taxonomy Tag Cloud\', array( \'description\' => \'Display a tag cloud for a custom taxonomy.\' ) );
}
/**
* Allows for manipulation, calculation, etc. when saving the widget instance in the dashboard.
*
* @param array $new_instance
* @param array $old_instance
*
* @return array
*/
function update( $new_instance, $old_instance ) {
return $new_instance;
}
/**
* Echos the widget contents in a sidebar
*
* @param array $args - the general widget arguments
* @param array $instance - the settings for this specific widget
*/
function widget( $args, $instance ) {
echo $args[\'before_widget\'];
echo $args[\'before_title\'] . \'Your widget title\' . $args[\'after_title\'];
$cloud_args = array( \'taxonomy\' => \'catalogtag\' );
wp_tag_cloud( $cloud_args );
echo $args[\'after_widget\'];
}
/**
* Render the "Controls" in the dashboard menu under Appearance => Widgets
*
* @param array $instance - the settings for this instance of the widget
*
* @return null
*/
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( \'title\' => \'\', \'taxonomy\' => \'post_tag\' ) );
// Load the list of taxonomies available
$taxonomies = get_taxonomies( array( \'public\' => TRUE , \'show_tagcloud\' => TRUE), \'objects\' );
echo \'<p><label>Title</label><input name="\' . $this->get_field_name( \'title\' ) . \'" id="\' . $this->get_field_id( \'title\' ) . \'" value="\' . esc_attr( $instance[\'title\'] ) . \'" /></p>\';
echo \'<p><label>Taxonomy</label><select name="\' . $this->get_field_name(\'taxonomy\') . \' id="\' . $this->get_field_id(\'taxonomy\') . \'">\';
echo \'<option value="">Select Taxonomy...</option>\';
foreach($taxonomies AS $tax) {
echo \'<option value="\' . $tax->name . \'"\';
echo ($tax->name == $instance[\'taxonomy\']) ? \' selected\' : \'\';
echo \'>\';
echo ( ! empty($tax->labels->singular_name)) ? $tax->labels->singular_name : $tax->label;
echo \'</option>\';
}
echo \'</select></p>\';
}
}
虽然从技术上讲,您可以将其添加到主题的函数文件中,但我倾向于将其放在单独的主题文件中(例如
widgets.php
, 并将该文件包含在函数文件中。