Best Practices for Using ACF Pro Securely in WordPress
ACF Pro is a powerful tool for WordPress developers, but without following security and performance best practices, your site may become vulnerable. Below, we’ll explore how to securely fetch and display images, links, text, and textarea fields using ACF Pro.
🔐 Common Security Tips
- Always escape output using the correct WordPress escape functions
- Never trust user-submitted data — always sanitize and validate
- Use
get_field()
to fetch ACF fields and escape outputs according to their context
🖼️ Image Field
The image field returns an array with url
and alt
. Always use esc_url()
and esc_attr()
for secure output.
$image = get_field('your_image_field');
if( $image ) {
$img_url = esc_url($image['url']);
$alt = esc_attr($image['alt']);
echo '<img src="' . $img_url . '" alt="' . $alt . '" />';
}
🔗 Link Field
The ACF link field returns an array containing url
, title
, and target
.
$link = get_field('your_link_field');
if( $link ):
$link_url = esc_url($link['url']);
$link_title = esc_html($link['title']);
$link_target = esc_attr($link['target'] ?: '_self');
echo '<a href="' . $link_url . '" target="' . $link_target . '">' . $link_title . '</a>';
endif;
📝 Text & Textarea Fields
Use esc_html()
for plain text fields. For textarea fields that may contain HTML, use wp_kses_post()
with wpautop()
to preserve formatting.
// For plain text
$text = get_field('your_text_field');
if( $text ) {
echo esc_html($text);
}
// For textarea with safe HTML
$textarea = get_field('your_textarea_field');
if( $textarea ) {
echo wp_kses_post(wpautop($textarea));
}
📂 Repeater Fields
Inside a Repeater field, use get_sub_field()
and escape each sub-field individually.
if( have_rows('your_repeater') ):
while( have_rows('your_repeater') ): the_row();
$sub_text = esc_html(get_sub_field('text'));
echo '<p>' . $sub_text . '</p>';
endwhile;
endif;
✅ Summary Table
Field Type | Function | Escape Function |
---|---|---|
Image | get_field() | esc_url(), esc_attr() |
Link | get_field() | esc_url(), esc_html(), esc_attr() |
Text | get_field() | esc_html() |
Textarea | get_field() | wp_kses_post(wpautop()) |
Repeater | get_sub_field() | esc_html() |