I have a simple custom widget that asks for its width (that is used later in the front end). The width field is a select dropdown, so a user have predefined options.
I will have many instances of my widget, each will have its own width setup.
Now, in my widget code I have the following code:
echo $before_widget;
which results in:
<div class="widget my" id="my-widget-1"></div>
What I’d like to do is somehow hook into $before_widget
and add my own class (the specified width from the select dropdown). So, I want the following markup:
<div class="widget my col480" id="my-widget-3"></div>
And if there is no class specified then I want to add class="col480"
.
How do I achieve this?
Thanks for help!
Dasha
Aha, so the
$before_widget
variable is a string representing div element:<div class="widget my" id="my-widget-1">
. So I checked the$before_widget
for the “class” sub-string and added my$widget_width
value to it.The code is from my custom widget file:
I wanted to add my
$widget_width
variable to the widget div element within my own widget code (while I had an easy access to the$widget_width
variable).Hope that makes sense and will help someone.
Thanks, Dasha
you can use
dynamic_sidebar_params
filter hook to find your widget and add your classes to it:Another way I found to add a class for a custom widget is to use the the ‘classname‘ key of your construct function like in:
And be sure to use default ‘before_widget‘ in your theme or if you use
register_sidebar()
in function.php, do it like this:Then on every instances of your widget, you will have the class ‘widget my-class-name’ like this:
You may also call the parent constructor first and then append whatever class name you want :
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
You can find the details with example at
http://satishgandham.com/2017/03/adding-dynamic-classes-custom-wordpress-widgets/
You can try this filter: