WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Alternative class to <li> using wp_list_categories() / 2 columns (5 posts)

  1. juxprose2
    Member
    Posted 4 years ago #

    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

  2. juxprose2
    Member
    Posted 4 years ago #

    I should probably add the HTML too:

    <ul class="left">
    <?php echo $cat_left; ?>
    </ul>
    
    <ul class="right">
    <?php echo $cat_right; ?>
    </ul>
  3. juxprose2
    Member
    Posted 4 years ago #

    Quick bump on this - any thoughts?

  4. Mark / t31os
    Moderator
    Posted 4 years ago #

    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;
    ?>
  5. juxprose2
    Member
    Posted 4 years ago #

    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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.