ACF - 根据转发器字段中的后端选择选项更改链接

时间:2015-05-20 19:15:32

标签: php wordpress foreach repeater advanced-custom-fields

我正在使用高级自定义字段来处理我网站上的许多内容。有一点特别是员工资料页面。我有一个选择字段,员工可以在其中添加社交图标或电子邮件图标。转发器字段是“社交”字段,如果他们选择“添加一行”,则存在“社交频道”选择字段和“社交链接”测试字段。我目前的代码是:

                <?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,但我不知道该怎么做。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您的选择字段应该只返回一个字符串,而不是数组(确保您将&#39; social_channel&#39;字段设置为不允许多个值),因此请将您的代码更改为这样:

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