This is how I register the sidebar:
register_sidebar(array(
'name' => 'First_sidebar',
'id' => 'sidebar-1',
'before_widget' => '<div class="well">',
'after_widget' => '</div>',
'before_title' => '<h4>',
'after_title' => '</h4>'
));
and this is the HTML WordPress output:
<div class="well">
<h4>title</h4>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
I want to add a class
attribute to the <ul>
tag.
Like this:
<div class="well">
<h4>title</h4>
<ul class="nav nav-list">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
How do I add the class
attribute to <ul>
?
The simple, but not so nice and more of a hack, is using Javascript/jQuery.
I really dislike using javascript, but it does the job in this case.
I managed to do it this way:
Sidebar.php:
I used output buffering to save the sidebar widgets into a variable and then used string replace to find all
<ul>
tags and replace them with the<ul>
tag with the class.Use Less:
it worked for me 😉
I played around with it and this works for me.
The parameter you are looking for is
'class' => ''
For you, you need:
That should work.
There is a native solution to add the individual widget names as className using sprintf to their container:
%1$s
represents the id and%2$s
the widgets classNameThere is no need to add the className directly to the
<ul>
because of this possible selector(jQuery/CSS):also note that the answered jQuery code targets all widgets in all sidebars, even if they are no nav-list (what can be OK if your only used widget is a nav).
Reference on wordpress.org
functions.php:
Output for a default navigation widget:
i am posting at this old thread because it was a top search result for the search term “register_sidebar widgetname” – so i thought having an complete answer is good here.
Use custom WordPress widget: (No need for jQuery or any Plugin!!)
My steps will go through with categories widget and you can do the same for any widget.
Copy file class-wp-widget-categories.php from /wp-includes/widgets/ and put it beside your theme files /wp-content/themes/-your theme-/widgets/
Include this file in functions.php
require_once('widgets/class-wp-widget-categories.php');
Rename class name from “WP_Widget_Categories” to “WP_Widget_Categories_Custom” in “widgets/class-wp-widget-categories.php” file.
class WP_Widget_Categories_Custom extends WP_Widget {
Search about ul tag in “widgets/class-wp-widget-categories.php” file and edit it like
<ul class="nav nav-list">
That is all 😉
This would replace all opening ul tags and li tags:
To Avoid conflicts with unwantend replacement i would recomment tu not use ul and li inside
‘before_widget’and ‘before_title’ like:
I was struggling against this problem and I discovered that you can use this plugin: http://wordpress.org/plugins/wp-bootstrap-navmenu
you can use a plugin that called widget-css-class
WordPress directory
after that you will be able to add custom css class to any widgets that you need.