RevealTheme logo
Back to Blog

WordPress And Custom Field Display In Themes

WordPress And Custom Field Display In Themes
The RevealTheme Team

By

··3 min read

Custom fields (via ACF, Meta Box, or native WordPress) store structured data attached to posts. Themes display the data; the display requires specific theme code or template adjustments.

The patterns that work produce clean display; the patterns that don't produce broken or empty displays.

The basic display pattern

In a theme template:

<?php $price = get_field('price'); ?>
<?php if ($price): ?>
    <p>Price: $<?php echo esc_html($price); ?></p>
<?php endif; ?>

The conditional check prevents output when the field is empty. The esc_html() escapes the value to prevent XSS.

The pattern is standard for ACF. Other custom field systems have similar patterns.

The conditional display

Always check whether the field has a value before displaying. Without the check: empty field produces "Price: $" with no value.

The conditional check is mechanical but easily forgotten. Every custom field display should include it.

The escaping discipline

Custom field values come from user input (through the editor). They could contain HTML or scripts.

Escape output appropriately: esc_html for text, esc_url for URLs, wp_kses_post for content with allowed HTML.

Forgetting to escape produces XSS vulnerabilities. The discipline matters even when the editor is trusted.

The repeater field pattern

ACF's repeater field stores arrays of sub-fields. The display pattern:

<?php if (have_rows('features')): ?>
    <ul>
    <?php while (have_rows('features')): the_row(); ?>
        <li><?php the_sub_field('feature_name'); ?></li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>

The loop iterates through the array; each iteration accesses sub-fields.

The relationship field display

Relationship fields store references to other posts. Displaying them requires fetching the referenced posts:

<?php $related = get_field('related_posts'); ?>
<?php if ($related): foreach ($related as $post): setup_postdata($post); ?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endforeach; wp_reset_postdata(); endif; ?>

The setup_postdata() sets up the global post variable for each iteration. The wp_reset_postdata() restores it after the loop.

The honest framing

Custom field display is a fundamental theme development skill. The patterns are well-documented but require discipline (conditional checks, escaping, proper loop handling).

For themes that display custom field data, the discipline produces robust display that handles edge cases (empty fields, malformed data) gracefully.