Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Any suggestions on the simplest way to display tags using get_tags in an html table (4 columns across) ?

Example:
Tag 1 | Tag2 | Tag 3 | Tag 4
Tag 5 | Tag 6 | Tag 7 | Tag 8

I'm using the following code to display tags, I found it in codex.:

    $tags = get_tags();
$html = '<div class="post_tags">';
foreach ($tags as $tag){
    $tag_link = get_tag_link($tag->term_id);

    $html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
    $html .= "{$tag->name}</a>";
}
$html .= '</div>';
echo $html;
share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

This is what I tried and it works well. I am using array_chunk, but I'm also adding a check to see if a chunk has less than 4 values (as you want 4 columns), then just add a blank <td>, which will avoid the mark up from breaking.

<?php
$tags = get_tags(array('hide_empty' => false));
$tag_groups = array_chunk($tags, 4);
$t = '<table>';
foreach($tag_groups as $tag_single)
{   
    $t .= '<tr>';
    for($i = 0; $i < 4; $i++)
    {
        if(isset($tag_single[$i]) && !empty($tag_single[$i]))
        {
            $tag_link = get_tag_link($tag_single[$i]->term_id);
            $t .= "<td><a href='".$tag_link."' title='".$tag_single[$i]->name."'>".$tag_single[$i]->name."</a></td>";
        }
        else
        {
            $t .= "<td></td>";
        }
    }
    $t .= '</tr>';
}

echo $t .= "</table>";
?>

Hope it helps!

share|improve this answer
    
That did the trick, answer accepted! I appreciate it, thanks. –  Pwn Oct 13 '11 at 7:35
    
You're welcome! :) –  Rutwick Gangurde Oct 13 '11 at 7:37
add comment

Well your code does not have any HTML tables but I will assume you still want tables and not DIV's.

The best way ( I think) is to use array_chunk , your example has 4 columns so something along the lines of (not tested);

<?php $tags = get_tags(); ?>

 <table>
   <?php foreach (array_chunk($tags, 4) as $row) {  ?>  <!-- 4 chunks-->
    <tr>
     <?php foreach ($row as $value) { ?>
      <td><?php echo $value; ?></td> <!-- or your $tag_link-->
     <?php } ?>
    </tr>
   <?php } ?>
</table>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.