0

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;
0

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!

0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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