首页 > 解决方案 > PHP / 高级自定义字段 (ACF) - 删除重复值

问题描述

我有一个网站,我在其中显示一个带有多个标签的书签列表,这是输出:

Bookmark Title
Link
Description text
#tag1 #tag2 #tag3 #tag4 #tag5

Bookmark Title
Link
Description text
#tag3 #tag4

Bookmark Title
Link
Description text
#tag1

(…)

我有一个过滤器,我可以在其中选择标签来隐藏/显示相应的书签。现在的问题是,当存在具有相同标签的书签时,标签也会在过滤器中重复,例如:

Filter: #tag1 #tag2 #tag3 #tag4 #tag5 #tag3 #tag4 #tag1

这是我的过滤器:

<div class="d-headline--update__filter">
        <?php if( have_rows('bookmark', 'option') ):?>
            Filter:
            <span class="filter__item filter__all active" onclick="filterSelection('all')">Show all</span>
            <?php while( have_rows('bookmark', 'option') ) : the_row();?>
                            <?php $bookmarkTags = get_sub_field('bookmark_tags', 'option');
                            if( $bookmarkTags ): ?>
                                <?php foreach( $bookmarkTags as $bookmarkTag ): ?>
                                    <span onclick="filterSelection('<?php echo $bookmarkTag; ?>')" class="filter__item filter__<?php echo $bookmarkTag; ?>"><?php echo $bookmarkTag; ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>
            <?php endwhile; ?>
        <?php endif; ?>
</div>

如何删除过滤器中的重复项?

标签: phpwordpressadvanced-custom-fields

解决方案


您需要跟踪已显示的标签,如果尚未跟踪,则有条件地显示标签。请参阅下面的一种方法,您可以这样做:

<div class="d-headline--update__filter">
  <?php if( have_rows('bookmark', 'option') ):?>
    Filter:
    <span class="filter__item filter__all active" onclick="filterSelection('all')">
      Show all
    </span>

    <?php 
    
    // collection of tags for this page
    $bookmarkTagsCollection = [];
    
    while( have_rows('bookmark', 'option') ) : the_row();?>
      <?php $bookmarkTags = get_sub_field('bookmark_tags', 'option'); ?> 
      
      <?php if ( $bookmarkTags ) : ?>

        <?php foreach( $bookmarkTags as $bookmarkTag ): ?>

          <?php // only display if this tag has not been displayed yet ?>

          <?php if (!in_array($bookmarkTag, $bookmarkTagsCollection)) : ?>
            <span onclick="filterSelection('<?php echo $bookmarkTag; ?>')" class="filter__item filter__<?php echo $bookmarkTag; ?>">
              <?php echo $bookmarkTag; ?>
            </span>

            <?php 
              // add current tag to collection to it does not get displayed again if later posts also contain this tag
              $bookmarkTagsCollection[] = $bookmarkTag;
            ?>
          <?php endif; ?>
        <?php endforeach; ?>

      <?php endif; ?>
    <?php endwhile; ?>
  <?php endif; ?>
</div>

推荐阅读