正在删除从自定义字段检索到的重复标题.Wordpress


Removing duplicate titles retrieved from custom fields. Wordpress

以下是从自定义选择字段检索状态名称并将其输出到导航菜单的代码。例如:如果纽约州下有5个职位,则此代码在导航下拉菜单中只显示一个纽约职位,因为多余的值被删除。。但我想做的是,当用户点击纽约时,它会重定向到一个新页面,在那里会显示纽约下的所有帖子。。所有状态也一样,因为这是一个动态菜单

                    $args = array('post_type' => 'article-form', 'showposts' => -1, 'orderby' => 'date', 'order' => 'DSC');
                    $city = new WP_Query($args);
                    $states = [];
                    while ( $city->have_posts() ) :
                        $city->the_post();
                        $state = get_field('state');
                        if ( !in_array($state, $states) ) :
                            $states[] = $state;
                            ?>
                            <li>
                                <a href="<?php the_permalink(); ?>" style="text-decoration: none; color: #9c9c9c;">
                                    <?php echo $state;
                                    ?>
                                </a>
                                <hr style="margin: 0">
                            </li>
                            <?php
                        endif;
                    endwhile; ?>
                    <?php wp_reset_query(); ?>
                </ul>

尝试将唯一值推入数组

<?php $stateArray = array(); ?>
<?php while ($city->have_posts()):$city->the_post(); ?>
<li>
    <a href="<?php the_permalink(); ?>" style="text-decoration: none; color: #9c9c9c; "> 
    <?php
        $state = the_field('state');
        if (!in_array($state, $stateArray)):
            echo $state;
            array_push($stateArray, $state);
        endif;
    ?>
    </a>
<hr style="margin:0">
</li>
<?php endwhile; ?>

我希望它能有所帮助!

p.S尽量避免内联css,使用和外部css文件进行任何类型的样式化。让你的html文件尽可能干净。

@user3127632将值推送到数组以检查它们以前是否打印过的想法很好,但他/她的代码中有几个错误。

如果你需要将ACF的字段值存储到变量中,你应该使用get_field()而不是the_field(),因为最后一个不返回值而是打印它。此外,你需要在条件中移动lia节点,否则你不会在链接中回显标签,但重复的链接仍然存在。。。

所以,它应该是这样的:

<?php 
$states = [];
while ( $city->have_posts() ) :
    $city->the_post();
    $state = get_field('state');
    if ( !in_array($state, $states) ) :
        $states[] = $state; // A more efficient way to push values to an array
?>
<li>
    <a href="<?php the_permalink(); ?>" style="text-decoration: none; color: #9c9c9c;">
        <?php echo $state; ?>
    </a>
    <hr style="margin: 0">
</li>
<?php
    endif;
endwhile;
?>

我希望这能有所帮助!