您可以为此创建一个自定义小部件。
// Widget Class ==============================
class WPSE154979_Widget extends WP_Widget
{
function WPSE154979_Widget()
{
$widget_ops = array(
\'classname\' => \'WPSE154979_custom_widget\',
\'description\' => __(\'Post Category Children\\\'s or Parent Categories\')
);
$control_ops = array( \'width\' => 200, \'height\' => 400);
$this->WP_Widget( \'WPSE154979_custom\', \'Custom Categories\', $widget_ops, $control_ops );
$this->alt_option_name = \'WPSE154979_custom\';
}
function widget( $args, $instance)
{
extract( $args);
$title = apply_filters( \'widget_title\', $instance[\'title\'], $instance, $this->id_base );
echo $before_widget;
if( $title )
echo $before_title . $title . $after_title;
// on single post page
if( is_single() && is_object_in_taxonomy( get_post_type(), \'category\' ) )
{
$cats = wp_get_object_terms(
get_the_ID(),
\'category\',
array( \'fields\' => \'ids\', \'orderby\' => \'count\', \'order\' => \'DESC\', )
);
$parent_id = array_shift( $cats );
wp_list_categories( \'title_li=&show_option_none=&hide_empty=0&parent=\'. $parent_id );
}
// on category page
elseif( is_category() )
{
$parent_id = (int) get_query_var(\'cat\');
wp_list_categories( \'title_li=&show_option_none=&hide_empty=0&parent=\'. $parent_id );
}
// on others page
else
{
$parent_id = 0;
wp_list_categories( \'title_li=&show_option_none=&hide_empty=0&parent=\'. $parent_id );
}
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance[\'title\'] = strip_tags( $new_instance[\'title\']);
return $instance;
}
function form( $instance )
{
$title = isset($instance[\'title\']) ? esc_attr($instance[\'title\']) : \'\'; ?><p>
<strong><?php _e( \'Title:\' ); ?></strong>
<br /><input class="widefat" id="<?php echo $this->get_field_id(\'title\'); ?>" name="<?php echo $this->get_field_name(\'title\'); ?>" type="text"
value="<?php echo $title; ?>" />
</p><?php
}
}
// Register Widget ==============================
add_action(\'widgets_init\', \'WPSE154979_Widget_Init\');
function WPSE154979_Widget_Init(){
register_widget( \'WPSE154979_Widget\' );
}
如果将上述代码添加到主题函数中。php文件,您将在
WP Admin -> Widgets
页将其拖放到适当的位置。