Some predefined widgets offer the option to use a select
element (dropdown) and/or a counter after each entry. How can I add the CSS classes widget-with-dropdown
or widget-with-counters
to these widgets?
There are already solutions for custom widgets, known sidebar ids or positions, but I have to inspect the parameters for the current instance, and I want to catch all possible positions or widgets (if they follow the WordPress naming scheme).
The CSS classes are applied in the function
dynamic_sidebar()
. There is no specific filter for that:But there is a filter for
$params
right after this code block:To get the settings for the current widget, we have to search in the global variable
$wp_registered_widgets
for an entry with the key$params[ 0 ][ 'widget_id' ]
.If it exists, it has a class instance as callback, and we can use that objectâs method
get_settings()
to ⦠well ⦠get the settings.The returned array has probably a key that equals
$params[1][ 'number' ]
.Associated with this key is an array again, and here we might find another key
dropdown
(orcount
) with a value of0
or1
.If it is
1
, we add the new classes to the string in$params[0]['before_widget']
.I think this easier to read as code:
Or, you can just use a plugin:
Both plugins are doing pretty much the same as @toscho showed in his answer.
Widget CSS Classes plugin
Source link to v1.2.1
Custom Widget Classes plugin
Source link to v1.1
Just to prove that @toscho is right and there seems to be no other option to go on this.
first add a custom placeholder class in the constructor
Then replace it with the class/es of your choice based on the widget options like this
We are using the place holder to limit the ways in which the html of before_widget may affect our plugin functionality
You can find the details with example at
http://satishgandham.com/2017/03/adding-dynamic-classes-custom-wordpress-widgets/