0

With the code below, I added a span tag + placed the category count inside the link.

add_filter('wp_list_categories', 'cat_count_span');    
function cat_count_span($links) {       
    $links = str_replace('</a> (', '<span>', $links);
    $links = str_replace(')', '</span></a>', $links);
    return $links;    
}

The problem I'm having... this modification will apply on all pages or widgets that uses wp_list_categories. And I'd like to have the opposite effect. The code should only apply inside my custom made category widget.

What do I need to change so it will work the way I'd like it to work?

1 Answer 1

0

Your widget must have a method that looks something like this:

public function widget( $args, $instance ) {
    echo $args['before_widget'];
    if ( ! empty( $instance['title'] ) ) {
        echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
    }
    wp_list_categories();
    echo $args['after_widget'];
}

Apply your filter inside that method, then remove it:

public function widget( $args, $instance ) {
    echo $args['before_widget'];
    if ( ! empty( $instance['title'] ) ) {
        echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
    }
    add_filter('wp_list_categories', 'cat_count_span'); 
    wp_list_categories();
    remove_filter('wp_list_categories', 'cat_count_span'); 
    echo $args['after_widget'];
}

The same thing works with the backend form method.

Reference:
https://codex.wordpress.org/Widgets_API#Example

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.