Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress How to add class to <ul> of sidebar widget

Tags:

wordpress

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>?

like image 608
Qing Avatar asked Jun 02 '13 16:06

Qing


People also ask

How do I add categories to my WordPress sidebar?

In the WordPress sidebar, hover over Appearance and select Widgets from the pop-out contextual menu. Drag and drop the Categories widget from the list of Available Widgets on the left side of the screen into a location on the right side of the screen, such as Default Sidebar.

How do I edit the sidebar widget in WordPress?

You can also edit the sidebar from the WordPress Dashboard. In the left-hand menu, select Appearance > Widgets, find the Sidebar section, and then give it a click to expand. You should now be able to see all the widgets that make up this particular sidebar.


2 Answers

The simple, but not so nice and more of a hack, is using Javascript/jQuery.

jQuery( document ).ready(function() {
    jQuery('.widget > ul').addClass('nav nav-list');
});

I really dislike using javascript, but it does the job in this case.

like image 159
toto_tico Avatar answered Sep 17 '22 13:09

toto_tico


I managed to do it this way:

Sidebar.php:

<!-- sidebar -->
<aside class="sidebar" role="complementary">

<div class="sidebar-widget">
  <?php if(function_exists('dynamic_sidebar')) {

    ob_start();
    dynamic_sidebar('widget-area-1');
    $sidebar = ob_get_contents();
    ob_end_clean();

    $sidebar_corrected_ul = str_replace("<ul>", '<ul class="menu vertical">', $sidebar);

    echo $sidebar_corrected_ul;
    } 

  ?>
</div>

</aside>
<!-- /sidebar -->

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.

like image 25
Yalung Tang Avatar answered Sep 17 '22 13:09

Yalung Tang