根据中继器字段的后端选择来更改链路


ACF - change link based on backend select choice in a repeater field

我在我的网站上使用高级自定义字段。有一件事特别适用于员工个人资料页面。我有一个选择字段,工作人员可以添加社交图标或电子邮件图标。中继器字段是"social",如果他们选择"添加一行",则有"social channel"选择字段和"social_link"测试字段。我现在的代码是这样的:

                <?php if ( have_rows('social')): ?>
                    <div class="staff-social">
                        <?php while ( have_rows('social')) : the_row() ?>
                            <li><a href="<?= the_sub_field('link'); ?>"><img src="<?= get_template_directory_uri(); ?>/img/footer-<?php the_sub_field('social_channel') ?>.svg" alt="social icon" /></a></li>
                        <?php endwhile; ?>
                    </div><!--end staff-social-->
                <?php endif; ?>

如果用户从后端'social_channel'下拉菜单中选择'mail',我需要在我的锚标记上添加'mailto:'。我试过了:

                       <?php while ( have_rows('social')) : the_row() ?>
                            <li>
                            <?php $select = get_sub_field_object('social_channel');
                            $choices = $select['choices']; 
                            foreach ($choices as $choice) {
                                if ($choice == 'mail') {
                                    echo '<a href="mailto:'.the_sub_field('link').'">';
                                } else echo '<a href="'.the_sub_field('link').'">';
                            } ?>
                            <img src="<?= get_template_directory_uri(); ?>/img/footer-<?php the_sub_field('social_channel') ?>.svg" alt="social icon" />
                            </a>
                            </li>
                        <?php endwhile; ?>

但是这当然会为所有的选择输出一些东西,不管它们是否被用户在后端选择。有人能帮我一下吗?我认为这是非常基本的PHP,但我不确定如何做到这一点。任何帮助将非常感激!

你的Select字段应该只返回一个字符串,而不是一个数组,(确保你将'social_channel'字段设置为不允许多个值)所以改变你的代码:

<?php while ( have_rows('social')) : the_row() ?>
        <li>
            <?php $select = get_sub_field('social_channel');
            if($select == 'mail'){ 
                $linkURL = 'mailto:'.get_sub_field('link');
            }else{
                $linkURL = get_sub_field('link');
            } ?>
            <a href="<?php echo $linkURL; ?>"><img src="<?= get_template_directory_uri(); ?>/img/footer-<?php the_sub_field('social_channel') ?>.svg" alt="social icon" /></a>
        </li>
<?php endwhile; ?>