0

I'm attempting to create a tag-based filter on a category page, so I only want to show those tags that are used by posts in that category.

I've got it mostly working, but the list isn't coming out alphabetical, and tags are repeated if they're used by more than one post. Here's my code:

        <ul class="dropdown filter option-set clearfix" data-filter-group="tags">
            <li><a href="#filter-tags-all" data-filter-value=".item" class="selected">All Tags</a></li>

            <?php $the_query = new WP_Query( 'posts_per_page=50&cat=89' ); ?>
            <?php if ( $the_query->have_posts() ) : ?>
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); 
                $posttags = get_the_tags();
                foreach($posttags as $posttag)
                {
                    echo "<li><a href='#filter-tags-" . $posttag->slug . "' data-filter-value='.".$posttag->slug."'>" . $posttag->name . "</a></li>";
                }
                endwhile;
            ?>
        </ul>

The issue seems to be that the foreach loop is within the while loop, so it's naturally echoing out the tags post by post. I can't figure out how to combine the results into one array.

I tried looping through $posttags and using array_merge as outlined here, but I couldn't get it to work.

Any ideas on how to combine the tags into one alphabetical list with no repeats would be much appreciated.

1 Answer 1

0

Try building a master $posttags array like so:

<?php 
$post_tags = array();
$the_query = new WP_Query( 'posts_per_page=50&cat=89' );
if ( $the_query->have_posts() ) : 
    while ( $the_query->have_posts() ) : $the_query->the_post(); 
        $posttags = get_the_tags();
        foreach( $posttags as $posttag )  {
            $post_tags[$posttag->slug] = $posttag->name;
        }
    endwhile;
endif;
?>

<ul class="dropdown filter option-set clearfix" data-filter-group="tags">
    <li><a href="#filter-tags-all" data-filter-value=".item" class="selected">All Tags</a>    </li>
    <?php  foreach( $post_tags as $tagslug => $tagname ){ ?>
        <li><a href="#filter-tags-<?php echo $tagslug;?>" data-filter-value="<?php echo     $tagslug;?>"><?php echo $tagname;?></a></li>
    <?php } ?>
</ul>
2
  • Thank you! That works perfectly. For anyone else who happens upon this: the only addition I made to the code above was to add natcasesort($post_tags); before the second foreach loop to sort the array alphabetically. Jan 13, 2015 at 15:09
  • I totally forget to add that to the code!
    – darrinb
    Jan 13, 2015 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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