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
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:
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.
Retrieve the code for the default category widget and insert it in your plugin. Rename the class to prevent conflicts.
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 thewp_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;
}
-
1I wonder if OP could use the
title_li
settings via thewidget_categories_args
filter? Regarding the replacement, can't we have more than one<ul>
from hierarchicalwp_list_categories()
output ? The fourth input argument ofpreg_replace()
is the replacements limit, that might become handy here, to account for that?– birgireDec 30, 2016 at 10:33 -
1@birgire You're certainly right about the 4th parameter to
preg_replace
: there would be moreul
's in the case of hierarchical display. I updated the answer to account for that.– cjbjDec 30, 2016 at 10:51 -
@birgire The
title_li
trick wouldn't really work, looking at line 566 ofwp_list_categories
. It is printend outside the hardcodedul
that starts the list. But perhaps you could modify that again with a filter.– cjbjDec 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?– crowdDec 30, 2016 at 16:33