- This topic has 3 replies, 2 voices, and was last updated 5 years, 4 months ago by
Elvin.
-
AuthorPosts
-
December 1, 2020 at 7:30 pm #1562613
George
I usually use this code when I want to hide a category from the categories widget:
function exclude_category_home( $query ) { if ( $query->is_home ) { $query->set( 'cat', '-5, -9, -23' ); } return $query; } add_filter( 'pre_get_posts', 'exclude_category_home' );I have a case, though, where I am using an element block that hooks into the right sidebar. In that block, I am using a category block to display all post categories. The above code doesn’t work in this case. I suspect it’s because the code is only relevant for actual widgets. Since I am replacing the widgets with a block element that contains Gutenberg blocks, I suspect the code won’t work. Any ideas?
December 1, 2020 at 8:43 pm #1562694Elvin
StaffCustomer SupportHi,
I find it strange that the snippet you’ve provided works for categories widget.
widget_categories_argsis normally the filter we use when we want to exclude categories on categories widget.I think this will give you a good idea why it doesn’t work.
https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-categories.phpThis is the official github page of WordPress. The link leads you directly to the PHP code of the categories widget.
On line 139, you’ll see that the widget uses
wp_list_categories()where its args are filtered withwidget_categories_args.This is the same case with the Category Block found here (line 49): https://github.com/WordPress/WordPress/blob/00680f2e89766e4ac9a71c68a8cccd3a141afb34/wp-includes/blocks/categories.php#L46
Which also uses
wp_list_categories()to list categories except here’s no filters.Read more about it here: https://developer.wordpress.org/reference/functions/wp_list_categories/
That said, consider writing your own shortcode that displays markup using the same function.
You can also try
get_categories()– https://developer.wordpress.org/reference/functions/get_categories/get_categories() exclusion – https://stackoverflow.com/a/26667662
December 2, 2020 at 4:19 am #1563435George
Hi Elvin. I apologize, I sent the wrong code. This is the code that works for widgets:
function custom_category_widget($args) { $exclude = "1, 12"; // Category IDs to be excluded $args["exclude"] = $exclude; return $args; } add_filter("widget_categories_args","custom_category_widget");I will have a look at the examples you provided and I am pretty sure I will come up with a solution.
Thanks for the pointers!
December 2, 2020 at 4:12 pm #1564738Elvin
StaffCustomer SupportAh right yeah, now that makes sense.
And as I’ve mentioned on the previous reply, it shows why it doesn’t work for category blocks. (no filters for it.)
It may be best to create a shortcode with atts that displays what you want (where atts is the exclusion $args).
No problem. 🙂
-
AuthorPosts
- You must be logged in to reply to this topic.