WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Alternative class to <li> using wp_list_categories() / 2 columns

[Resolved] Alternative class to <li> using wp_list_categories() / 2 columns

  • juxprose2
    Member

    @juxprose2

    Hello

    I am using this snippet of code to output wp_list_categories() over two columns:

    $string_categories200809 = "echo=0&depth=1&style=none&show_option_all=&title_li=&hide_empty=1&child_of=".CAT_SCHOOLS_200809;
    $cats = explode('<br />', wp_list_categories($string_categories200809));
                    $cat_n = count($cats) - 1;
                    for ($i = 0; $i < $cat_n; $i++):
                    if ($i < $cat_n/2):
                    $cat_left = $cat_left.'<li>'.$cats[$i].'</li>';
                    elseif ($i >= $cat_n/2):
                    $cat_right = $cat_right.'<li>'.$cats[$i].'</li>';
                    endif;
                    endfor; ?>

    This outputs into two columns nicely.

    However, I would also like to add a class of “alt” to every other list item, so I can “zebra-stripe” the list, as is often done with tabular data.

    Any ideas? I am think $count could be key here, but really don’t know where to start.

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • juxprose2
    Member

    @juxprose2

    I should probably add the HTML too:

    <ul class="left">
    <?php echo $cat_left; ?>
    </ul>
    
    <ul class="right">
    <?php echo $cat_right; ?>
    </ul>
    juxprose2
    Member

    @juxprose2

    Quick bump on this – any thoughts?

    Check if $i is odd or even, and do whatever..

    if( $i % 2 ) :
      // $i is odd
    else :
      // $i is even
    endif;
    
    // Or shorthand ternary
    $var = ( $i % 2 ) ? 'is odd' : 'is even';

    Example inside your code.

    for( $i = 0; $i < $cat_n; $i++ ) :
    	$class = ( $i % 2 ) ? '' : ' class="alternate"';
    
    	if( $i < ( $cat_n / 2 ) ) :
    		$cat_left = $cat_left.'<li'.$class.'>'.$cats[$i].'</li>';
    	elseif( $i >= ( $cat_n / 2 ) ) :
    		$cat_right = $cat_right.'<li'.$class.'>'.$cats[$i].'</li>';
    	endif;
    endfor;
    ?>

    juxprose2
    Member

    @juxprose2

    That’s great – thanks very much!

    I also found a jQuery solution:

    $(document).ready(function() {
    	$('ul li:odd').addClass('odd');
    	$('ul li:even').addClass('even');
    });

    Many thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘[Resolved] Alternative class to <li> using wp_list_categories() / 2 columns’ is closed to new replies.