I created a widget by extending WP_Widget
, works well.
Also added a field to the admin called className
.
But I can’t find any hook where I can inject the custom CSS class name into the rendering code of the widget (I want the class to be applied to the whole widget of course).
// Before widget.
echo $before_widget;
if ($title)
{ echo $before_title.$title.$after_title; }
if ($headline)
{ echo '<h4>'.$headline.'</h4>'; }
if ($description)
{ echo '<p>'.$description.'</p>'; }
if ($className)
{ echo '<p>Class name: '.$className.'</p>'; }
// After widget.
echo $after_widget;
The HTML output for this goes like:
<aside id="eppz-page-widget-2" class="widget widget_eppz-page-widget">
<h3 class="widget-title">Title</h3>
<h4>Headline!</h4>
<p>Some description that can be added optionally to the widget.</p>
<p>Class name: featuredPageWidget</p>
</aside>
Now I really want to append the className
variable after all the classes applied to aside
. I could do it with some string functions, but I’d really hope that there is a simple WordPressy way to do this.
As I really had no intention to override default template
before_widget
injections, I came up with a quirky workaround, that still do not touch template implementation.I use a placeholder as the class name, then simply replace it in rendering code.
Set up a readonly class property:
Set is as the classname for the widget at construction time:
Replace placeholder with the widget parameter at render:
And there.
Whatever is the actual
before_widget
implementation, this approach safely sets the custom class name (seeMyCustomClassName
below) for the whole widget: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/