Code Snippets

A curated collection of 40 ready-to-use ACF code snippets covering everything from basic field retrieval to advanced block registration, REST API integration, and WooCommerce customisation. Each snippet is tested, well-documented, and designed to be dropped straight into your theme or plugin.

Curated by Hookturn | | 40 snippets
adminblocksconfigurationfield-typeshooksjsonoptionsqueryingrest-apiwoocommerce
php configuration

Check if ACF is Active Before Using Its Functions

Safely call ACF functions without fatal errors when the plugin is deactivated.

if ( class_exists( 'ACF' ) ) {
    $value = get_field( 'hero_title' );
    echo esc_html( $value );
}
php field-types

Create a Front-End Form with ACF

Use acf_form() to build front-end forms for submitting or editing posts with ACF fields.

// At the very top of your page template (before get_header).
acf_form_head();
get_header();
?>
php blocks

Create an ACF Block with InnerBlocks

Enable InnerBlocks within an ACF block to allow nesting other Gutenberg blocks inside your custom block.

{
    "name": "acf/hero",
    "title": "Hero Section",
    "category": "theme",
php json

Use Human-Readable ACF JSON Filenames

Replace default ACF JSON filenames like group_64a1b2c3.json with readable names for cleaner version control diffs.

add_filter( 'acf/json/save_file_name', function ( $filename, $post, $load_path ) {
    $filename = str_replace(
        [
            ' ',
php blocks

Detect Preview Mode in ACF Block Templates

Use the $is_preview variable to render different output in the editor vs the front end.

/**
 * Google Map Block Template.
 *
 * @param array $block The block settings and attributes.
php woocommerce

Display ACF Fields on WooCommerce Product Pages

Add custom ACF field data to WooCommerce single product pages using hooks.

add_action( 'woocommerce_single_product_summary', function () {
    $specs = get_field( 'technical_specs' );

    if ( $specs ) {
php field-types

Display an ACF Gallery Field as a Responsive Image Grid

Loop through a gallery field and output responsive images with srcset using wp_get_attachment_image().

$gallery = get_field( 'photo_gallery' );

if ( $gallery ) : ?>
    <div class="gallery-grid">
php field-types

Display ACF Select and Checkbox Field Labels

Get the human-readable label of a select or checkbox field choice rather than the stored value.

$field  = get_field_object( 'colour' );
$value  = $field['value'];
$label  = $field['choices'][ $value ] ?? '';
php hooks

Dynamically Populate an ACF Select Field's Choices

Use the acf/load_field filter to populate a select, checkbox, or radio field with dynamic options.

add_filter( 'acf/load_field/name=related_service', function ( $field ) {
    $field['choices'] = [];

    $posts = get_posts( [
php rest-api

Expose ACF Fields in the WordPress REST API

Make ACF field data available in WordPress REST API responses for headless and decoupled builds.

add_action( 'acf/init', function () {
    acf_add_local_field_group( [
        'key'                   => 'group_my_fields',
        'title'                 => 'My Fields',
php rest-api

Fetch ACF Options Page Fields via REST API

Create a custom REST endpoint to expose ACF options page values — not available by default in the REST API.

add_action( 'rest_api_init', function () {
    register_rest_route( 'mysite/v1', '/options', [
        'methods'             => 'GET',
        'callback'            => function () {
php rest-api

Format ACF Field Values in REST API Responses

Control how ACF fields are serialised in REST API responses — return full objects instead of IDs for images, posts, and other relational fields.

GET /wp-json/wp/v2/posts/123?acf_format=standard
php options

Get ACF Field Values from an Options Page

Retrieve field values stored on an ACF options page from anywhere in your theme or plugin.

$phone   = get_field( 'company_phone', 'option' );
$email   = get_field( 'company_email', 'option' );
$address = get_field( 'company_address', 'option' );
php field-types

Get ACF Fields from Taxonomy Terms

Retrieve ACF fields attached to categories, tags, and custom taxonomy terms using the term ID prefix.

// Get a field from a specific term.
$term_id    = 42;
$color      = get_field( 'brand_color', 'term_' . $term_id );
$icon       = get_field( 'icon', 'term_' . $term_id );
php field-types

Get ACF Fields from User Profiles

Retrieve ACF fields attached to user profiles using the user ID prefix syntax.

$user_id = 5;
$bio     = get_field( 'biography', 'user_' . $user_id );
$photo   = get_field( 'profile_photo', 'user_' . $user_id );
$title   = get_field( 'job_title', 'user_' . $user_id );
php field-types

Get an ACF Image Field with All Sizes

Retrieve image field data and output specific image sizes with proper alt text and responsive srcset.

$image = get_field( 'hero_image' );

if ( $image ) : ?>
    <img
php blocks

Get the Additional CSS Class on an ACF Block

Access the 'Additional CSS class(es)' value from the block sidebar to apply custom styles in your render template.

/**
 * Card Block Template.
 *
 * @param array $block The block settings and attributes.
php hooks

Get All Fields from a Field Group Programmatically

Use acf_get_fields() to retrieve all field definitions from a specific field group for dynamic forms, exports, or documentation.

$fields = acf_get_fields( 'group_event_details' );

if ( $fields ) {
    foreach ( $fields as $field ) {
php querying

Include ACF Fields in WordPress Search Results

Extend WordPress search to include ACF field values so custom field content appears in search results.

add_filter( 'posts_join', function ( $join, $query ) {
    global $wpdb;

    if ( $query->is_search() && $query->is_main_query() && ! is_admin() ) {
php field-types

Loop Through an ACF Repeater Field

The canonical pattern for iterating over ACF repeater field rows, including nested repeaters.

if ( have_rows( 'team_members' ) ) : ?>
    <ul class="team-list">
        <?php while ( have_rows( 'team_members' ) ) : the_row(); ?>
            <li>
php hooks

Programmatically Update ACF Fields

Use update_field() and update_sub_field() to set ACF field values from code, with the correct value formats for each field type.

$post_id = 123;

// Text, textarea, number, email, URL.
update_field( 'company_name', 'Acme Corp', $post_id );
php querying

Query Posts by ACF Field Values with WP_Query

Use meta_query in WP_Query to filter and sort posts by ACF field values.

$posts = new WP_Query( [
    'post_type'  => 'event',
    'meta_query' => [
        [
php querying

Query Posts by ACF Relationship Field

Reverse-query posts that reference a specific post in an ACF Relationship or Post Object field.

// Find all posts that reference post ID 42 in their 'related_articles' field.
$related = new WP_Query( [
    'post_type'  => 'post',
    'meta_query' => [
php configuration

Register an ACF Field Group via PHP

Define a complete ACF field group programmatically using acf_add_local_field_group() for version-controlled, portable field definitions.

add_action( 'acf/init', function () {
    acf_add_local_field_group( [
        'key'      => 'group_event_details',
        'title'    => 'Event Details',
php blocks

Register an ACF Block with block.json

Register a custom Gutenberg block using ACF's block.json method — the recommended approach since ACF 6.0.

{
    "name": "acf/testimonial",
    "title": "Testimonial",
    "description": "A custom testimonial block.",
php hooks

Run Code After ACF Fields Are Saved

Use the acf/save_post action to execute custom logic after ACF fields are saved, with the correct priority to avoid common pitfalls.

add_action( 'acf/save_post', function ( $post_id ) {
    // Skip if this is an autosave, revision, or ACF options page save you don't want.
    if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
        return;
php

Store ACF pro license key in WordPress PHP configuration

// Add this in your wp-config.php file
define('ACF_PRO_LICENSE', '{YOUR LICENSE KEY HERE}' );
php

How to update an ACF Google Map field programmatically using PHP

// The field accepts a value with this structure
$value = [
php

Register a super simple toolbar for ACF's WYSIWYG field

Need a custom WYSIWYG toolbar configuration? Use this snippet.

add_filter( 'acf/fields/wysiwyg/toolbars', function ( $toolbars ) {
php

Load ACF JSON files from multiple locations

Use these snippets to load ACF JSON files from more than one directory

add_filter( 'acf/settings/load_json', function ( $paths ) {
php

Split an ACF Flexible content field into Template Parts

If you're working on a project with lots of Flexible content field 'rows' it can really help to break them into template parts

// In a post/page template, loop over the ACF flexible field layouts and load the partial
// responsible for rendering the layout. 
while ( the_flexible_field('my_flexi_field') ) {
	get_template_part( 'components/'. get_row_layout() );
php

Hide the ACF Admin Menu Item on Selected Sites

A snippet to hide the ACF 'Custom Fields' menu item from the wp-admin area.

add_filter( 'acf/settings/show_admin', function () {


	// Get the current site url.
php

Convert an ACF Field Group from PHP to ACF-JSON

Use this snippet to convert legacy field groups from PHP to ACF-JSON files

// Get all the local field groups and loop through them for processing.
$field_groups = acf_get_local_field_groups();
foreach ( $field_groups as $group ) {
php

Register Google Maps API Key for ACF

Register & define a Google Maps API key to allow the location field to work correctly.

// Define this in the site's wp-config.php file.
define('GOOGLE_API_KEY', 'your-google-api-key-here');
php

Register an ACF Options Page

Use these snippets to register an ACF options pages

// register a top-level options page
if ( function_exists( 'acf_add_options_page' ) ) {
php

Speed up ACF backend loading time

Drastically speed up the load times of the post edit page!

add_filter('acf/settings/remove_wp_meta_box', '__return_true');

Stay Updated

Get ACF tips and new extensions in your inbox

No spam. Unsubscribe anytime.