首页 WordPress函数大全 the_sub_field()

the_sub_field()

2020-06-28 / 1294阅 / 悠然

如何你看完本文还不知道如何使用该函数,可以联系我定制视频教程,50元/个函数,学不会全额退款

描述

显示来自“中继器”或“灵活内容”字段循环的特定子字段值的值。

此功能与基本上相同echo get_sub_field()

参量

the_sub_field( $selector, [$format_value] ); 
  • $selector (字符串) (必需) 子字段名称或字段关键字。
  • $format_value (布尔) (可选) 是否应用格式化逻辑。默认为true。

例子

在“中继器”字段中显示一个值。

本示例说明如何循环显示“中继器”字段并显示子字段值。

<?php if( have_rows('todo') ): ?>
    <ul>
    <?php while ( have_rows('todo') ) : the_row(); ?>
        <li><?php the_sub_field('item'); ?></li>
    <?php endwhile; ?>
    </ul>
<?php else : ?>
    <p>No todos found.</p>
<?php endif; ?> 

在“弹性内容”字段中显示一个值。

本示例说明如何循环显示“灵活内容”字段并为不同的布局生成HTML。

<?php if( have_rows('content') ): ?>
    <?php while( have_rows('content') ): the_row(); ?>
        <?php if( get_row_layout() == 'paragraph' ): ?>
            <?php the_sub_field('paragraph'); ?>
        <?php elseif( get_row_layout() == 'quote' ): ?>
            <blockquote>
                <p><?php the_sub_field('quote'); ?></p>
                <footer>—<?php the_sub_field('author'); ?></footer>
            </blockquote>
        <?php endif; ?>
    <?php endwhile; ?>
<?php endif; ?> 

嵌套循环

本示例说明如何遍历嵌套的Repeater字段并显示子字段值。

<?php 

/**
 * Field Structure:
 *
 * - locations (Repeater)
 *   - title (Text)
 *   - description (Textarea)
 *   - staff_members (Repeater)
 *     - image (Image)
 *     - name (Text)
 */
if( have_rows('locations') ): ?>
    <div class="locations">
    <?php while( have_rows('locations') ): the_row(); ?>
        <div class="location">
            <h3><?php the_sub_field('title'); ?></h3>
            <p><?php the_sub_field('description'); ?></p>
            <?php if( have_rows('staff_members') ): ?>
                <ul class="staff-members">
                <?php while( have_rows('staff_members') ): the_row();
                    $image = get_sub_field('image');
                    ?>
                    <li>
                        <?php echo wp_get_attachment_image( $image['ID'], 'full' ); ?>
                        <h4><?php the_sub_field('name'); ?></h4>
                    </li>
                <?php endwhile; ?>
                </ul>
            <?php endif; ?>
        </div>
    <?php endwhile; ?>
    </div>
<?php endif; ?> 
大家谈论
    我的见解