'mnmlwp_colored_categories', 'description' => 'A list of categories styled with the selected category color.', ); parent::__construct( 'mnmlwp_colored_categories', esc_html__('mnmlWP Colored Categories', 'mnmlwp'), $widget_options ); $this->widget_folder = get_template_directory_uri() . '/widgets/mnmlwp-colored-categories/'; $this->enqueue_scripts_and_styles(); } private function enqueue_scripts_and_styles() { wp_enqueue_style( 'mnmlwp-colored-categories', $this->widget_folder . 'mnmlwp-colored-categories-style.css' ); } public function widget( $args, $instance ) { $instance_title = isset( $instance['title'] ) ? $instance['title'] : ''; $instance_num_cats = isset( $instance['num_cats'] ) ? $instance['num_cats'] : 5; $instance_hide_empty = isset( $instance['hide_empty'] ) ? $instance['hide_empty'] : false; $instance_colorize = isset( $instance['colorize'] ) ? $instance['colorize'] : false; $title = apply_filters( 'widget_title', $instance_title, $instance, $this->id_base ); $num_cats = (int)$instance_num_cats; if( $num_cats === -1 ) $num_cats = 99999999; $hide_empty = filter_var( $instance_hide_empty, FILTER_VALIDATE_BOOLEAN ); $colorize = filter_var( $instance_colorize, FILTER_VALIDATE_BOOLEAN ); echo $args['before_widget']; if( ! empty( $title ) ) { echo $args['before_title']; echo $title; echo $args['after_title']; } $categories = get_terms( 'category', array( 'orderby' => 'count', 'hide_empty' => absint( $hide_empty ), 'number' => $num_cats, ) ); if( empty( $categories ) ) { echo '…'; echo $args['after_widget']; return; } foreach( $categories as $cat ) { $term_id = $cat->term_id; $cat_meta = get_option( "category_$term_id" ); $cat_count = $cat->count; $color = isset( $cat_meta['color'] ) ? $cat_meta['color'] : '#0073aa'; $text_color = $colorize ? $cat_meta['color'] : 'inherit'; $style = 'background:' .$color; echo ''; echo '' . esc_attr( $cat->name ) . ''; echo '' . $cat_count . ''; echo ''; } echo $args['after_widget']; } /** * Back-end widget form. * * @see WP_Widget::form() * * @param array $instance Previously saved values from database. */ public function form( $instance ) { $title = ! empty( $instance['title'] ) ? apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) : ''; $num_cats = ! empty( $instance['num_cats'] ) ? (int)$instance['num_cats'] : 5; $hide_empty = ! empty( $instance['hide_empty'] ) ? (int)$instance['hide_empty'] : 0; $colorize = ! empty( $instance['colorize'] ) ? (int)$instance['colorize'] : 0; ?>

>

>

99999999 ) $instance['num_cats'] = 99999999; $instance['hide_empty'] = ( ! empty( $new_instance['hide_empty'] ) ) ? absint( $new_instance['hide_empty'] ) : ''; $instance['colorize'] = ( ! empty( $new_instance['colorize'] ) ) ? absint( $new_instance['colorize'] ) : ''; return $instance; } } add_action( 'widgets_init', function() { return register_widget('mnmlWP_Widget_Colored_Categories'); });