30% OFF FLASH SALE on AVF Pro – HURRY! Sale Ends in:

0

Days

:

0

Hrs

:

0

Mins

:

0

Secs

Shop now!
WPLake > Learning Hub > ACF Select Field: Complete Guide with Code Snippets

ACF Select Field: Complete Guide with Code Snippets

The essentials to enhance ACF Select fields with dynamic choices, AJAX loading, nested selects, and code snippets to simplify display and query tasks.

Key Points at a Glance

  1. Dynamic Choices: Choices for the ACF Select field can be generated dynamically using filters, allowing options to be pulled from various sources like post types or image sizes.
  2. AJAX Option: When enabled, the AJAX option improves performance by loading options dynamically and filtering results in real-time as the user types.
  3. Nested Selects: Although ACF’s default Select field doesn’t support nested options, you can use the optgroup HTML element with a custom load filter to implement grouped options.
  4. Querying Data: Depending on where the ACF Select field is used (posts, terms, user profiles), querying for field values can be handled with WP_Query, WP_Term_Query, or WP_User_Query classes.
  5. Alternative Fields: For selecting posts, users, or taxonomies, using ACF’s Post Object, Relationship, User, or Taxonomy fields is recommended for better functionality and performance.

Table of Contents

ACF Select is a field type in the Advanced Custom Fields plugin that belongs to the Choice group. This field enables editors (or users) to make selections from a predefined list.

ACF Select field UI

ACF Select Field
You can define the selection choices statically in the settings or dynamically in the code
ACF Select field look for editors
Default editor's appearance of the ACF select field
The stylized UI option enhances the appearance and functionality of the Select field by adding a search.

ACF Select field-related addons

ACF addons can be an important part of the workflow, and there are several addons especially useful for the ACF Select field:

  • ACF City Selector adds a new field type to Advanced Custom Fields, allowing users to select cities based on country and province/state.
  • ACF Image Size Select plugin adds an Image Size field type to ACF, allowing you to select from all registered image sizes within the WordPress dashboard.
  • ACF: Gravity Forms Add-on integrates Gravity Forms seamlessly with ACF. This plugin introduces a custom ACF field type that allows you to select and link a Gravity Form within your ACF field groups.
  • ACF Field For Contact Form 7 adds a custom field type for integrating Contact Form 7 forms with Advanced Custom Fields. This plugin allows you to store one or more Contact Form 7 forms in an ACF field and easily manage their visibility.
  • ACF Quick Edit Fields enhances the WordPress admin experience by adding Quick Edit functionality to Advanced Custom Fields. This plugin allows you to quickly view and edit ACF field values directly from the list views.
  • ACF Tooltip enhances the user experience by managing lengthy instruction texts in ACF fields. Instead of cluttering the edit screen, this plugin allows you to add tooltips to field labels, keeping the interface clean and space-efficient.
  • WPGraphQL for ACF allows you to expose ACF fields and field groups to GraphQL, enabling seamless querying of ACF data within your GraphQL queries.

Select fields in other meta-field plugins

If you're looking for ACF alternatives, the ACF Select field is similar to the Select field in the Meta Box plugin and the Relationship field in the Pods plugin. Read our comparison of the best meta field plugins to learn about the differences between vendors.

1. ACF Select field essentials

1.1) Field settings

Primary settings

  1. Choices
    The Choices setting allows you to define the options available in the Select field. Each choice is a value-label pair. The field saves only the value in the database, while editors use the label. You can add choices manually, or dynamically generate them using a filter if needed.
  2. Select Multiple Values
    The Select Multiple Values option determines whether editors can select more than one option from the list. When enabled, the Select field becomes a multi-select field, allowing users to choose multiple items by holding down the Ctrl (Windows) or Command (Mac) key while clicking.
  3. Stylized UI
    The Stylized UI option enhances the appearance and functionality of the Select field by transforming it into a more modern, user-friendly interface. This setting utilizes the Select2 JavaScript library, adding advanced features such as search, AJAX loading, and the ability to reorder selections. When enabled, the Select field adopts a stylized dropdown with search capabilities, allowing editors to quickly find and select options, even from long lists. Additionally, this setting changes how the Allow Null feature works, replacing the default “- Select -” label with an ‘x’ icon, which editors can use to clear their selection effortlessly.
  4. Allow Null
    The Allow Null setting, when enabled, permits the Select field to have no value selected. If you select this option, the list will start with an empty choice labeled “- Select -,” allowing the editor to skip making a choice if it's not required. When you enable the Stylized UI setting, this empty choice turns into an ‘x’ icon, so the editor can easily remove any selected value(s) and leave the field empty.

Secondary settings

  1. Default Value
    The Default Value setting allows you to specify a pre-selected option or set of options when the field is first displayed. This is useful if you want to provide a default choice to guide the user or ensure that the editor always selects a certain value unless he changes it manually.
  2. Return Format
    The Return Format setting controls how ACF functions return the selected value(s). You can choose to return either the value, label, or both. This is particularly useful if you need to use the selected data in a specific format in your theme or plugin.
  3. AJAX Option
    The AJAX option enhances the Select field's usability, especially when dealing with a large number of choices. When enabled, the field will load options dynamically via AJAX, reducing the initial load time and improving performance. This feature also enhances the user experience by filtering and displaying options in real-time as the user types.

1.2) Storage format and supported field locations

Regardless of the field settings, the ACF Select field saves only the value in the database. If the field allows only a single selection, the system stores the value as a string.

ACF Select field value in the DB
In the database, ACF saves only the field value.

If the field settings allow multiple selections, it stores the values as a serialized array:

a:2:{i:0;s:6:"value1";i:1;s:6:"value2";}

The Select field can be used in various locations, but it always stores data in the same format.

Field locations

You can add the Select field to the following locations:

  1. Post Objects (Post, Page, Media Attachment, CPT Item, WooCommerce Product)
    In WordPress, all content types, including pages and media attachments, are stored in the wp_posts table. The editor used - whether Gutenberg, Classic Editor, or a Page Builder - does not impact how the data is saved. The ACF Select field's value is stored in the wp_postmeta table, associated with the target post or custom post type (CPT) item.
  2. Options Page
    ACF provides an Options Page feature, enabling the storage of global site-wide settings. When you add a Select field to an Options Page, ACF stores its value in the wp_options table, making global data easy to access and manage.
  3. User Profiles
    ACF lets you add the Select field to user profiles, allowing you to store user-specific data. In this case, the system stores the value in the wp_usermeta table, associated with the corresponding user.
  4. Terms (e.g., Post Categories)
    You can also add the Select field to terms, such as post categories, tags, or custom taxonomies. When used with a term, the system stores the value in the wp_termmeta table, linked to the specific term.
  5. ACF Gutenberg Block
    ACF enables you to add the Select field to custom ACF blocks. When used within an ACF Block, the value is stored within the post_content as part of the block's JSON data structure, making it part of the block's content in the wp_posts table.

1.3) Return value formats

The Return Format setting of the ACF Select field determines how the selected value(s) are returned when using the get_field() function in your theme or plugin.

Note that if you enable the Select Multiple Values option, the return format will be an array, containing the responses in the selected return format:

  1. Value
    When the Value option is selected, the get_field() function will return only the value of the selected option.
  2. Label
    Selecting the Label option means that get_field() will return the label associated with the selected value(s).
  3. Value and Label
    The Value and Label option returns an array where each selected value is paired with its corresponding label. The array is structured as ['value' => x, 'label' => y], with each key representing a selected value and each corresponding value representing the label.

1.4) Alternative field types

If you need to select objects such as posts, users, or taxonomies, consider using the ACF Post Object, Relationship, User, or Taxonomy fields. These field types are specifically designed for handling object selections within WordPress, providing more tailored functionality for these use cases.

2. Use cases of the ACF Select field

The ACF Select field is versatile and can be applied in various scenarios. Here are some common use cases:

  1. Static Choice Input
    Ideal for scenarios where you need a fixed set of options, such as selecting a car vendor from a predefined list. On the front end, users or editors can easily select from these static choices.
  2. Conditional Fields
    The Select field can be used in the conditional logic rules to show or hide different fields or groups of fields based on the selected value. For example, if you're managing car settings, you can display different configuration options depending on the chosen car vendor. This allows for a dynamic form experience tailored to the selected choice.
  3. Dynamic Choice Input
    When you need the options to be generated dynamically based on other data, such as selecting image dimensions from those registered on the website, the Select field can be configured to pull in these options. This makes the field adaptable to various data sources and ensures that choices are always relevant.
  4. Input in ACF Forms
    You can use the Select field within ACF forms to collect user input. It means you can leverage ACF's form functionality to create frontend forms for users to submit or edit content. The Select field provides a structured way to capture predefined choices in these forms. For more details on setting up ACF forms, you can refer to ACF Form Documentation.

3. Misuse of the ACF Select field

The ACF Select field is versatile, but certain scenarios are better handled by other ACF field types or WordPress features. Here are common misuse cases and alternative solutions:

  1. Populating a select field with titles from another post type
    If you need to create a dropdown list populated with titles from another post type, it's more appropriate to use the ACF Post Object field or Relationship field. These fields are designed specifically for selecting and linking to posts or custom post types, offering more robust functionality for this purpose.
  2. Populating a select field with user names
    When you need to populate a dropdown with user names, the ACF User field is the better choice. This field is tailored to handle user data and allows for the selection of users by their names or IDs, making it more suitable than the Select field for this purpose.
  3. Filtering large item sets with Meta Query
    When filtering items based on custom fields or metadata, using WP Taxonomy is more efficient, especially with large datasets. Meta queries require extensive database searches, while, in contrast, taxonomies (such as categories and tags) are optimized for querying and filtering. Therefore, if your goal includes not just displaying values but also sorting or filtering large amounts of content, always use taxonomy for better performance and scalability. You can add new taxonomies using the ACF Taxonomy feature or using the register_taxonomy function.

4. ACF Select field support in Themes and Builders

ACF is one of the most popular WordPress plugins, and it's supported by many page builders right out of the box. However, most of these integrations are basic, providing limited control over layout or lacking support for advanced field types like Gallery or Repeater.

To achieve universal compatibility with any theme and page builder while gaining advanced control over your layout, consider using the Advanced Views Framework or custom code snippets as discussed in the following chapter.

Here's a snapshot of the built-in features offered by some of the most popular WordPress themes and page builders for displaying ACF Select fields:

Theme/BuilderACF-related featureACF Select type support
Astra-no
AvadaDynamic Contentno (not declared)
BeaverACF Moduleyes
BricksDynamic datano (not declared)
DiviACF Moduleno (not declared)
ElementorDynamic Tagsno (not declared)
GeneratePress-no
Gutenberg-no
KadenceDynamic Contentno (not declared)
OceanWP-no
Visual ComposerDynamic Contentno (not declared)
WPBackery-no

While this list may seem brief, many themes come with their own page builders. Check your theme’s documentation for guidance on displaying ACF Select fields, or refer to the universal methods outlined below for a more flexible approach.

5. Code snippets for the ACF Select field

ACF functions and their responses are essentially wrappers around built-in WordPress features. This means that to load and display field values, you need to be familiar not only with ACF but also with core WordPress classes and functions. Additionally, writing markup from scratch and manually escaping data can be time-consuming.

To streamline development, you can use the Advanced Views Framework. This WordPress framework offers smart templates for the front end, simplifying post queries and template creation. It generates default markup and automatically loads the escaped data into the template, allowing you to focus on the layout itself.

Unlike drag-and-drop page builders, smart templates in Advanced Views are modular and based on a template engine (Twig or Blade), providing full control over the markup and helping you avoid the pitfalls of global CSS and JavaScript files. The framework natively supports all ACF field types, along with other data sources.

Below are examples for both Advanced Views and custom code:

5.1) Loading and displaying the field value

Using Advanced Views Framework

  1. Navigate to the Views section and create a new View.
  2. Choose the Select field in the Fields tab.
  3. Save the View, and the template will be automatically generated. You can copy and modify this template as needed.
  4. To integrate it into your page, either paste the generated shortcode or enable the Custom Gutenberg block option.

Loading from different locations: To load a field from different locations (e.g., user profile), use the object-id shortcode argument.

Using custom code

The ACF get_field function response will differ based on whether the field allows multiple selections and the chosen return format.

Note that the single or multiple option setting affects the return format, not the number of selected items. For example, even if only one item is selected but the return format is set to multiple, the response will be an array.

1. Single with the "Value" return format (Default):

$value = get_field('your_select_field'); // from the current post
$value = get_field('your_select_field', 10); // from a specific post by ID
$value = get_field('your_select_field', 'option'); // from the options page
$value = get_field('your_select_field', 'user_1'); // from the user by ID
$value = get_field('your_select_field', 'category_2'); // from the category term with ID 2
$value = get_field('your_select_field', 'genre_3'); // from the custom genre term with ID 3
echo esc_html($value); // Outputs the selected value

2. Single with the "Label" return format:

$label = get_field('your_select_field'); // from the current post
$label = get_field('your_select_field', 10); // from a specific post by ID
$label = get_field('your_select_field', 'option'); // from the options page
$label = get_field('your_select_field', 'user_1'); // from the user by ID
$label = get_field('your_select_field', 'category_2'); // from the category term with ID 2
$label = get_field('your_select_field', 'genre_3'); // from the custom genre term with ID 3
echo esc_html($label); // Outputs the selected label

3. Single with the "Label and Value" return format:

$choice = get_field('your_select_field'); // from the current post
$choice = get_field('your_select_field', 10); // from a specific post by ID
$choice = get_field('your_select_field', 'option'); // from the options page
$choice = get_field('your_select_field', 'user_1'); // from the user by ID
$choice = get_field('your_select_field', 'category_2'); // from the category term with ID 2
$choice = get_field('your_select_field', 'genre_3'); // from the custom genre term with ID 3

$value = $choice['value'] ?? ''; // Extract the value
$label = $choice['label'] ?? ''; // Extract the label

echo $value . ' - ' . $label; // Outputs the value and its label

4. Multiple with the "Value" return format:

$values = get_field('your_select_field'); // from the current post
$values = get_field('your_select_field', 10); // from a specific post by ID
$values = get_field('your_select_field', 'option'); // from the options page
$values = get_field('your_select_field', 'user_1'); // from the user by ID
$values = get_field('your_select_field', 'category_2'); // from the category term with ID 2
$values = get_field('your_select_field', 'genre_3'); // from the custom genre term with ID 3

if (is_array($values)) {
    foreach ($values as $value) {
        echo esc_html($value); // Outputs each selected value
    }
}

5. Multiple with the "Label" return format:

$labels = get_field('your_select_field'); // from the current post
$labels = get_field('your_select_field', 10); // from a specific post by ID
$labels = get_field('your_select_field', 'option'); // from the options page
$labels = get_field('your_select_field', 'user_1'); // from the user by ID
$labels = get_field('your_select_field', 'category_2'); // from the category term with ID 2
$labels = get_field('your_select_field', 'genre_3'); // from the custom genre term with ID 3

if (is_array($labels)) {
    foreach ($labels as $label) {
        echo esc_html($label); // Outputs each label of the selected values
    }
}

6. Multiple with the "Value and Label" return format:

$choices = get_field('your_select_field'); // from the current post
$choices = get_field('your_select_field', 10); // from a specific post by ID
$choices = get_field('your_select_field', 'option'); // from the options page
$choices = get_field('your_select_field', 'user_1'); // from the user by ID
$choices = get_field('your_select_field', 'category_2'); // from the category term with ID 2
$choices = get_field('your_select_field', 'genre_3'); // from the custom genre term with ID 3

if (is_array($choices)) {
    foreach ($choices as $choice) {
        $value = $choice['value'] ?? ''; // Extract the value
        $label = $choice['label'] ?? ''; // Extract the label
        echo esc_html($value) . ' - ' . esc_html($label); // Outputs each value and its label
    }
}

5.2) Displaying all the available choices

In some cases, you might need to display not just the selected value or label but the entire list of available choices. This can be particularly useful when using ACF forms or when you need to display all options for a field.

Using Advanced Views Framework

The Advanced Views Framework provides a built-in choices property for the Select field, which allows you to easily loop through all available options.

Using custom code

The ACF API includes the get_field_object() function, which allows the retrieval of the field info. Here’s how you can use it:

$all_choices = get_field_object('my_select')['choices'] ?? [];
foreach ($all_choices as $choice_value => $choice_label) {
    echo esc_html($choice_value) . ' - ' . esc_html($choice_label) . '<br>'; // Outputs each choice value and its label
}

5.3) Setting choices dynamically

To set the choices of an ACF Select field dynamically, you can use the acf/load_field filter. This allows you to define the choices of a field dynamically. These choices will be available for both editors and on the front (in the get_field_object function).

Below are examples of dynamically setting choices for a Select field based on different criteria:

Basic example

add_filter('acf/load_field/name=my_select_field', function (array $field):array {
    // Your dynamic choices here
    $field['choices'] = array(
        'value1' => 'Label 1',
        'value2' => 'Label 2',
    );

    return $field;
});

Example 1: List of post types

To populate a Select field with a list of registered post types, use the following code:

add_filter('acf/load_field/name=post_type_select', function (array $field):array {
    // Get all public post types
    $post_types = get_post_types(array('public' => true), 'objects');
    $field['choices'] = array();
    
    foreach ($post_types as $post_type) {
        $field['choices'][$post_type->name] = $post_type->label;
    }
    
    return $field;
});

Example 2: Image sizes

To populate a Select field with the registered image sizes:

add_filter('acf/load_field/name=image_size_select', function (array $field):array {
    // Get all image sizes
    $image_sizes = get_intermediate_image_sizes();
    $field['choices'] = array();
    
    foreach ($image_sizes as $size) {
        $field['choices'][$size] = $size;
    }
    
    return $field;
});

Example 3: WordPress menu names

To populate a Select field with the names of registered WordPress menus:

add_filter('acf/load_field/name=menu_select', function (array $field):array {
    // Get all registered menus
    $menus = wp_get_nav_menus();
    $field['choices'] = array();
    
    foreach ($menus as $menu) {
        $field['choices'][$menu->term_id] = $menu->name;
    }
    
    return $field;
});

Then to display the chosen menu, you can use the following function:

/**
 * Display the chosen menu based on the ACF select field.
 *
 * @param string $field_name The ACF field name that contains the menu ID.
 * @return string The HTML output of the menu or a message if not found.
 */
function display_chosen_menu(string $field_name):string {
    // Fetch the selected menu ID
    $menu_id = get_field($field_name);

    // Return early if no menu ID is selected
    if (!$menu_id) {
        return 'No menu selected.';
    }

    // Retrieve the menu object
    $menu = wp_get_nav_menu_object($menu_id);

    // Return early if menu not found
    if (!$menu) {
        return 'Menu not found.';
    }

    // Capture the menu output
    ob_start();
    wp_nav_menu(array(
        'menu' => $menu_id,
        'menu_class' => 'your-menu-class', // Optional: add a CSS class to the menu
        'container' => 'nav', // Optional: wrap the menu in a <nav> element
        'container_class' => 'your-container-class' // Optional: add a CSS class to the container
    ));
    return (string)ob_get_clean();
}

5.4) Setting nested select (Optgroup)

The default ACF Select field displays a basic HTML select dropdown that allows users to choose a single option. When you enable the "Stylized UI" option, it leverages the Select2 library, which adds features like search functionality - beneficial for long lists of items.

However, both the default and Stylized UI options lack built-in support for grouping options. If you need to group options within a Select field (e.g., grouping cities by country), you can use the <optgroup> HTML element, which is supported in plain HTML select elements but not directly available in ACF's Select field.

Fortunately, there is a way to implement this feature using the load filter. Here’s how you can achieve nested options using a hook:

add_filter('acf/load_field/name=my_select', function (array $field):array {
    $field['choices'] = [
        'Country1' => [
            'city1' => 'City 1',
            'city2' => 'City 2',
        ],
        'Country2' => [
            'city3' => 'City 3',
            'city4' => 'City 4',
        ],
        'other'  => 'Other City',
    ];

    return $field;
});

This example requires a dynamic option definition. If you wish to extend the default static defining, check the nested select example from wptips.

5.5) Updating the select field programmatically

To update the Select field programmatically, you can use the ACF update_field function. Since this field always stores the option value, the data you pass must be an option value.

In case you've enabled the multiple options setting for the field, you should pass an array, instead of the string, as shown below:

add_action('acf/init', function() {
    // for the fields without the multiple option
    update_field('my_select_field', 'my_option', 1); // update 1 to the target post id

     // for the fields with the multiple option
    update_field('my_select_field', ['my_option',], 1); // update 1 to the target post id
});

If you need to update the Select field on a user or term object, you must add the appropriate prefix, just as shown in the "loading" field value section.

Note: You should call the update_field function inside the acf/init action, or in any hooks that happen later.

6. Querying by the ACF Select field

When working with the ACF Select field, you might need to find items based on a specific select value. Unlike displaying select field values, querying items by these values can be more complex due to varying storage locations for ACF fields.

Here’s how to handle queries depending on where the Select field values are stored:

6.1) By postmeta (Post, Page, Any CPT)

Using Advanced Views Framework:

If you're using the AVF: Pro edition, querying by ACF Select field values is straightforward with Meta Queries. You need to create a Card, choose the target Select field in the Meta Fields tab, and define the desired value. It can be a static string or pointer to another field. Then the framework will take care of the rest.

Using WP_Query

For custom queries, you can use the built-in WP_Query class:

$args = array(
    'post_type' => 'post', // or your CPT
    'post_status' => 'publish',
    'posts_per_page' => -1, // means unlimited
    'meta_query' => array(
        array(
            'key'   => 'your_select_field',
            'value' => 'selected_value',
             // use 'LIKE' as the comparison in case your field supports multi-select
            'compare' => '='
        )
    )
);
$query = new WP_Query($args);
foreach($query->get_posts() as $post){
 // todo WP_Post $post
}

6.2) By termmeta (Terms)

Here we need to employ the WP_Term_Query class:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'your_select_field',
            'value'   => 'selected_value',
             // use 'LIKE' as the comparison in case your field supports multi-select
            'compare' => '='
        )
    )
);

$term_query = new WP_Term_Query($args);

foreach ($term_query->get_terms() as $term) {
    // Process each WP_Term object
    // Example: echo $term->name;
}

6.3) By usermeta (user profile)

In this case, we need to use the WP_User_Query class:

$args = array(
    'meta_key'     => 'your_select_field',
    'meta_value'   => 'selected_value',
   // use 'LIKE' as the comparison in case your field supports multi-select
    'meta_compare' => '='
);
$user_query = new WP_User_Query($args);

foreach ($user_query->get_results() as $user) {
    // Process each WP_User object
    // Example: echo $user->user_login;
}

6.4) Inside ACF Blocks

ACF Blocks save their data as JSON in the post_content. This data cannot be queried directly. However, if you enable the "Save in Meta" feature for ACF Blocks, the field values are also saved in post meta, allowing you to query them similarly to other postmeta fields.

7. Related Select field filters and hooks

ACF offers a variety of filters and hooks that enable you to modify field data and behavior, extending WordPress's core hooks functionality. You can utilize the standard add_action and add_filter functions to attach custom code to these hooks.

Below are some of the most commonly used hooks along with the ACF Select field type:

7.1) acf/load_field

The acf/load_field filter allows you to modify the field settings before it is displayed. You can use it to define a custom choices list, as we showed before with image sizes:

add_filter('acf/load_field/name=image_size_select', function (array $field):array {
    // Get all image sizes
    $image_sizes = get_intermediate_image_sizes();
    $field['choices'] = array();
    
    foreach ($image_sizes as $size) {
        $field['choices'][$size] = $size;
    }
    
    return $field;
});

7.2) acf/render_field

The acf/render_field action allows you to add custom HTML before or after a field's input on the editor's screen in the WordPress admin. This can be particularly useful for adding custom-styled text, icons, styles, or additional interactive elements to enhance the field's functionality.

// todo replace field key with yours
add_action('acf/render_field/key=field_123456789abc', function (array $field):void {
	// todo your custom HTML
	echo '<div class="my-custom-class">Custom field-related element</div>';
});

Note: By default, the acf/render_field action is triggered after the field input has been printed. If you need to print your HTML before the input, you should set the priority number to 9 or lower in the third argument of the add_action WordPress function.

7.3) acf/validate_value

Use the acf/validate_value filter to validate the values entered into the field. You can ensure that the entered value meet specific criteria:

add_filter('acf/validate_value/name=my_select_field', function($valid, $value, array $field) {
    if (true !== $valid) {
        return $valid; // Skip validation if there is an existing error
    }

    // todo your custom validation
    if (false === my_custom_value_validation($value)) {
        $valid = 'Invalid value selected';
    }

    return $valid;
}, 10, 3);

7.4) acf/validate_save_post

The acf/validate_save_post action allows you to perform custom form validations before saving ACF fields. This is particularly useful when you need to validate one field's value based on another field's input or enforce specific rules across multiple fields.

Suppose you have two select fields in your form: one for selecting a Department and another for selecting a Team within that department. You want to ensure that the selected team corresponds to the chosen department:

add_action('acf/validate_save_post', function () {
    // Get values from the select fields
    $department = $_POST['acf']['field_123456789abc'] ?? ''; // Replace with your Department field key
    $team = $_POST['acf']['field_abcdef123456'] ?? '';       // Replace with your Team field key

    // Define compatible values for each department (example data)
    $compatible_teams = [
        'sales' => ['sales_team_1', 'sales_team_2'],
        'marketing' => ['marketing_team_1', 'marketing_team_2'],
        // Add more departments and their compatible teams as needed
    ];

    // Check if the selected team is compatible with the chosen department
    if (isset($compatible_teams[$department]) && !in_array($team, $compatible_teams[$department], true)) {
        // Add a validation error if the values are not compatible
        acf_add_validation_error('field_abcdef123456', 'The selected team does not match the chosen department.');
    }
});

Tip: To find the field key, navigate to the ACF field group in the WordPress admin. Click on the Screen Options button at the top right corner of the page, then check the Field Keys option. Once enabled, the field keys will be displayed next to each field name in the group.

7.5) acf/save_post

The acf/save_post action is triggered when the current item (page/product/user) is saved. You can use it to perform any additional actions.

Let’s say you have a select field in your form where editors can choose a Project Status (e.g., "In Progress," "Completed," "On Hold"). When the status is set to "Completed," you want to send a notification email to the project manager:

add_action( 'acf/save_post', function ( $post_id ) {
	// Get the value of the select field
	$project_status = get_field( 'project_status', $post_id ); // Replace with your Select Field key

	// Check if the status is "Completed"
	if ( 'completed' !== $project_status ) {
		return;
	}

	// Retrieve the project manager's email (adjust this part based on your field setup)
	$manager_email = get_field( 'project_manager_email', $post_id ); // Replace with the manager's email field key
	$manager_name  = get_field( 'project_manager_name', $post_id );  // Replace with the manager's name field key

	// Prepare the email content
	$subject = "Project Status Update: Completed";
	$message = "Hello {$manager_name},\n\nThe project has been marked as completed.";

	// Send an email to the project manager
	wp_mail( $manager_email, $subject, $message );
} );

Note: The acf/save_post action is triggered every time the editor presses the Update button, meaning the code will run even if there were no changes in the target field. To ensure the action is executed only once, you can add a separate ACF field, such as isNotificationSent, and update that field after sending. This approach helps prevent duplicate actions.

Stuck with development or facing an issue?

WPLake offers affordable on-demand website development and design.

No matter the size of your project - contact us now, and we'll get it done for you!

Get assistance now

FAQ mode

/

Learning mode

  1. Can editors add their own options?

    No, the ACF Select field does not support adding custom options. It is limited to selecting only from a predefined list. If you need a field that allows editors to add custom options, use the ACF Checkbox field instead. This field supports custom values through the "Allow Custom Values" setting, which can be enabled in the Validation tab.

  2. Can the Select field be turned into an image select?

    Though having the ability to choose among images might be helpful in scenarios like selecting a map marker icon, ACF does not offer a built-in image select feature. If this functionality is crucial for your project, you might consider using the Meta Box plugin, which provides an Image Select field. This field type allows editors to select from a list of images, offering a more visual selection process.

  3. Is there a way to load select values depending on the values in another field?

    There is no direct way to dynamically load select values based on other fields or selects. Even with AJAX loading enabled, you can only retrieve pre-saved values and not dynamically change options based on current selections. A potential workaround is to use conditional logic. This involves defining multiple select fields and using conditional rules to show or hide specific selects based on user input.

  4. Can I translate select choices in a multilingual website?

    Yes, multilingual plugins like Polylang and WPML allow you to translate select choices. You should keep the values consistent across languages and translate only the labels. This approach ensures that editors see the correct labels while editing, and you maintain uniform values in the code. For detailed instructions, refer to the guides for Polylang and WPML.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Related articles

Content links (79)

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly


    Got it