0

The Category widget shows the list of existing categories. I need this list to begin with "All posts", with the count of all posts in the brackets.

1 Answer 1

1

If the default category widget's interface doesn't offer what you want, there are roughly two courses of action: find another widget or adapt the existing one. The first would be outside the scope of this site, the second one is a bit too broad, but here's what you would do for big adaptations:

  1. Build the basic code for a plugin to insert your own widget in. If you know your php you can learn this in ten minutes.

  2. Retrieve the code for the default category widget and insert it in your plugin. Rename the class to prevent conflicts.

  3. Adapt the code to insert "All posts" as a list item before the call to wp_list_categories. If you're using drowpdowns it's more complicated, because you will need to delve into the wp_dropdown_categories function.

Note that both latter functions end with filters that let you change the output. If you are sure this won't interfere with other calls to these functions, you could add a filter in the functions.php of your theme to do the modification. This might be pragmatic, but it is also risky. Untested example:

add_filter ('wp_list_categories', 'wpse250758_add_all_posts');
function wpse250758_add_all_posts ($output) {
  $count = wp_count_posts();
  preg_replace ('<ul>','<ul><li>All Posts ('. $count->publish .  ')</li>', $output,1);
  return $output;
  }
4
  • 1
    I wonder if OP could use the title_li settings via the widget_categories_args filter? Regarding the replacement, can't we have more than one <ul> from hierarchical wp_list_categories() output ? The fourth input argument of preg_replace() is the replacements limit, that might become handy here, to account for that?
    – birgire
    Dec 30, 2016 at 10:33
  • 1
    @birgire You're certainly right about the 4th parameter to preg_replace: there would be more ul's in the case of hierarchical display. I updated the answer to account for that.
    – cjbj
    Dec 30, 2016 at 10:51
  • @birgire The title_li trick wouldn't really work, looking at line 566 of wp_list_categories. It is printend outside the hardcoded ul that starts the list. But perhaps you could modify that again with a filter.
    – cjbj
    Dec 30, 2016 at 10:56
  • Then is there a way to add a count of all posts to the menu item "Blog" in my sidebar?
    – crowd
    Dec 30, 2016 at 16:33

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.