Black Friday 50% OFF! Coupon “BLACKFRIDAY50” Ends in:

0

Days

:

0

Hrs

:

0

Mins

:

0

Secs

Shop now!
WPLake > Learning Hub > ACF True/False Field: Complete Guide with Code Snippets

ACF True/False Field: Complete Guide with Code Snippets

Explore the ACF True/False field: customizable UI, binary choices, conditional logic for dynamic visibility, querying options, and icon displays.

Key Points at a Glance

  1. Field Type: The ACF True/False field is a binary choice field that displays as a checkbox or toggle switch, used for simple yes/no or true/false decisions.
  2. Stylized UI: The field can be customized with a Stylized UI option, transforming it from a default checkbox to a more visually appealing toggle switch with customizable labels.
  3. Data Storage: Values are stored as strings '1' (true) and '0' (false) in the database, though they are converted to PHP booleans when retrieved.
  4. Conditional Logic: The field can be used with ACF's conditional logic to dynamically show or hide other fields based on its value.
  5. Querying: Querying by True/False values involves handling data in different locations (postmeta, termmeta, usermeta) and can be managed through both Advanced Views Framework and WP_Query.

Table of Contents

The ACF True/False is a field type in the Advanced Custom Fields plugin, categorized under the Choice fields group. This field type provides a simple way for editors to make binary decisions, typically represented as yes/no, true/false, or on/off.

It appears as a checkbox or a toggle switch, offering a straightforward and user-friendly interface for setting options.

ACF True/False field UI

ACF True False field
General settings of the True/False field.
Presentation settings of the ACF True False field
The presentation settings allow you to enable the Stylized UI, which transforms the mundane browser checkbox into a beautiful switcher.
Default look for editors of the ACF True false field
By default, the True/False field is a default browser checkbox.
Styled UI look for editors of the ACF True False field
The Stylized UI option allows you to transform the input into a beautiful switcher with an option for custom Yes/No labels.

ACF True/False field-related addons

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

  • 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.

True/False fields in other meta-field plugins

If you're exploring alternatives to ACF, the ACF True/False field closely resembles the Switch field in the Meta Box plugin and the Yes/No field in the Pods plugin. These fields offer similar functionality, allowing for quick binary choices within your custom fields.

For a deeper dive into how these plugins compare, check out our comprehensive guide on the best meta-field plugins, where we break down the key differences between each vendor.

1. ACF True/False field essentials

1.1) Field settings

The ACF True/False field includes several specific settings beyond the standard field name and label:

General tab

  1. Message:
    This option allows you to display a custom message next to the checkbox. It's useful for adding context or clarifying the purpose of the field.
  2. Default Value:
    Sets the initial state of the checkbox when the field loads the first time. You can choose to have the checkbox checked or unchecked by default, depending on your needs.

Presentation tab

  1. Stylized UI:
    Enabling this setting transforms the basic checkbox into a sleek toggle switch, enhancing the visual appeal and user experience. ACF uses the Select2 library, which powers this switch.
  2. On/Off Text:
    When you enable the Stylized UI, this setting lets you customize the text displayed for each switch state. Instead of a generic true/false label, you can use personalized terms like Yes/No, Enabled/Disabled, or any other pair that suits your context.

1.2) Storage format and supported field locations

Regardless of the field settings, the ACF True/False field stores the 'yes' option as '1' and the 'no' option as '0' in the database. Since the meta_value column in WordPress has a string type, it stores these values as strings ('1' and '0').

ACF True False value in the DB
The unchecked value of the True/False field in the DB.

This behavior is important to keep in mind when comparing values directly in a MySQL query, as you’ll be working with string data rather than numeric or boolean types.

Supported field locations

The ACF True/False field can be used in various contexts, and it consistently stores values regardless of where the field is applied:

  1. Post Objects (Post, Page, Media Attachment, CPT Item, WooCommerce Product):
    The True/False field can be applied to any post type, including pages, media attachments, and custom post types, all stored in the wp_posts table. The true/false values are saved in the wp_postmeta table, linked to the relevant post or custom post type item.
  2. Options Page:
    The True/False field can be used on an ACF Options Page, storing its value in the wp_options table. This is ideal for global settings like toggling a feature site-wide, such as enabling/disabling maintenance mode.
  3. User Profiles:
    When added to user profiles, the True/False field's values are stored in the wp_usermeta table, associated with the respective user. This can be useful for settings like user preferences or account status toggles.
  4. Terms (e.g., Post Categories):
    The True/False field can be attached to taxonomy terms, such as categories, tags, or custom taxonomies. In this case, the values are stored in the wp_termmeta table, connected to the specific term, which can be useful for toggling term-specific settings.
  5. ACF Gutenberg Block:
    When used within custom ACF blocks, the True/False field's values are embedded in the post_content as part of the block's JSON data structure in the wp_posts table. This approach integrates the field's state directly into the block's content.

1.3) Return value format

Although the True/False field stores '1' and '0' as strings in the database, retrieving the field value with the ACF get_field() function automatically converts these strings into PHP booleans: '1' is returned as true, and '0' as false. This seamless conversion ensures the correct data type is used in your PHP logic, simplifying your code and reducing the need for manual type casting or checks.

$is_checked = get_field('my-true-false-field');

// to make sure the field is checked compare with true
if(true === $is_checked) {
// todo
}

// to make sure the field is unchecked compare with false
if(false === $is_checked) {
// todo
}

1.4) Alternative field types

The True/False field lets you select between two binary options. If you need more than two choices or wish to define custom string values (instead of 1/0), consider using the ACF Select field.

The Select field allows you to specify multiple options and customize both the labels and values, offering greater flexibility for more complex decision-making scenarios.

2. Use cases of the ACF True/False field

The ACF True/False field is highly versatile and can be used in a variety of scenarios:

  1. Toggling Features On and Off
    Use the True/False field to control features on your website, such as enabling or disabling a maintenance mode, turning on a special promotion, or showing/hiding specific content elements.
  2. Conditional logic for field visibility
    Leverage the True/False field with ACF's conditional logic to dynamically show or hide other fields within a group. For example, you can create a setup where additional fields only appear if the True/False field is set to true.
  3. User preferences
    This field is perfect for capturing user preferences, like subscribing to newsletters, opting into dark mode, or allowing location access.
  4. Custom post status
    You can use this field to set a custom status for posts or products, such as marking a post as “featured” or a product as “on sale.” This allows for easy filtering and display of content with specific attributes.
  5. Gutenberg block settings
    When used in ACF custom blocks, the True/False field can manage block settings, like enabling animations, displaying additional options, or altering the layout of the block.

3. ACF True/False 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 True/False fields:

Theme/BuilderACF-related featureACF True/False 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 True/False fields, or refer to the universal methods outlined below for a more flexible approach.

4. Code snippets for the ACF True/False 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:

4.1) Loading and conditional displaying

The ACF True/False field is commonly used to conditionally display elements based on its value. Here are two popular examples: displaying a label and adding a class conditionally.

Using Advanced Views Framework

  1. Navigate to the Views section and create a new View.
  2. Select the True/False field in the Fields tab.
  3. Save the View; a template will be automatically generated. Amend the template as shown below.
  4. To integrate it into your page, paste the generated shortcode or use 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.

Template for displaying a label conditionally:

<p>The event is {% if true_false.value %}open{% else %}closed{%endif %}.</p>

Template for adding a class conditionally:

<p class="{% if true_false.value %}event-open{% else %}event-closed{%endif %}">
Event status</p>

Using custom code

To load the field value, use the ACF get_field() function. By default, this function retrieves the value for the current item (post/product). If you need to get the value from a different source, you can specify the source using the second argument, as shown below.

Add the following code to the relevant template file of your theme:

Displaying a label conditionally:

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

$label = true === $is_checked ? 'open' : 'closed';

printf('<p>The event is %s.</p>', esc_html($label));

Adding a class conditionally:

// Replace 'my_true_false' with your field name
$is_checked = get_field('my_true_false'); 
$class = true === $is_checked ? 'event-open' : 'event-closed';

printf('<div class="%s">Event Status</div>', esc_attr($class));

4.2) Displaying check/cross icon

In addition to conditional usage, the True/False field can be visually represented as a check or cross icon. This approach provides a clear, visual way to display binary information.

Using Advanced Views Framework

To display the check/cross icon, we'll use the conditional class template to control the class, as shown in the AVF True/False Docs:

<div class="switcher switcher--state--{% if true_false.value %}checked{% else %}unchecked{% endif %}"></div>

And now we can add the CSS code, to display UTF-8 icons conditionally:

.switcher {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
}

.switcher--state--checked::after {
    content: "\2713"; /* Check mark */
    color: green;
}

.switcher--state--unchecked::after {
    content: "\00D7"; /* Cross mark */
    color: red;
}

Using custom theme code

Initially, we need to display a div, with a conditional class. We'll use the same approach, as used before:

// Replace 'my_true_false' with your field name
$value = get_field('my_true_false'); 
$state = $value ? 'checked' : 'unchecked';

printf('<div class="switcher switcher--state--%s"></div>', esc_attr($state));

Now, we can display icons depending on the class. For this example, we've used the UTF check and cross icons. Add the following CSS to your theme:

.switcher {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
}

.switcher--state--checked::after {
    content: "\2713"; /* Check mark */
    color: green;
}

.switcher--state--unchecked::after {
    content: "\00D7"; /* Cross mark */
    color: red;
}

4.3) Updating the True/False field programmatically

To update the True/False field programmatically, you can use the ACF update_field function. Since this field is a boolean, the data you pass must be a PHP boolean value.

add_action( 'acf/init', function () {
	// Replace 'my_true_false_field' with your field name,
	// and 1 with the source post ID (where the value will be updated)
	update_field( 'my_true_false_field',
		true,
		1
	);
} );

If you need to update the True/False 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.

5. Querying by the ACF True/False field

When working with the ACF True/False field, you might need to find items based on their checked/unchecked state. Unlike displaying check or cross icons, querying items by these values can be more complex due to the various locations where ACF fields are stored.

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

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

Using Advanced Views Framework:

If you're using the AVF: Pro edition, querying by ACF True/False field values is straightforward with Meta Queries. You need to create a Card, choose the target True/False field in the Meta Fields tab, and define the desired value. It can be a static value (1/0) or a 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_true_false_field',
            'value' => '1', //  use 0 for unchecked state
        )
    )
);
$query = new WP_Query($args);
foreach($query->get_posts() as $post){
 // todo WP_Post $post
}

Note: The code provided searches for items with a saved value of '1' (true). If you need to find items that have either a value of '0' (false) or no value at all, use the following snippet:

$args = array(
    'post_type'      => 'post', // or your Custom Post Type (CPT)
    'post_status'    => 'publish',
    'posts_per_page' => -1, // Retrieve all posts
    'meta_query'     => array(
        'relation' => 'OR', // To combine multiple meta queries
        array(
            'key'     => 'your_true_false_field', // Replace with your field name
            'value'   => '0', 
        ),
        array(
            'key'     => 'your_true_false_field', // Replace with your field name
            'compare' => 'NOT EXISTS' // Include items where the field does not exist
        )
    )
);

$query = new WP_Query($args);

foreach ($query->get_posts() as $post) {
    // Process WP_Post object
    // For example, display the post title
    echo '<p>' . get_the_title($post->ID) . '</p>';
}

5.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_true_false_field',
            'value' => '1', //  use 0 for unchecked state
        )
    )
);

$term_query = new WP_Term_Query($args);

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

Note: The code provided searches for items with a saved value of '1' (true). If you need to find items that have either a value of '0' (false) or no value at all, use the following snippet:

<?php
$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        'relation' => 'OR', // Combine multiple meta queries
        array(
            'key'     => 'your_true_false_field', // Replace with your field name
            'value'   => '0',
        ),
        array(
            'key'     => 'your_true_false_field', // Replace with your field name
            'compare' => 'NOT EXISTS' // Include terms where the field does not exist
        )
    )
);

$term_query = new WP_Term_Query($args);

foreach ($term_query->get_terms() as $term) {
    // Process each WP_Term object
    // Example: echo $term->name;
    echo '<p>' . esc_html($term->name) . '</p>';
}
?>

5.3) By usermeta (user profile)

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

$args = array(
    'meta_key'     => 'your_true_false_field',
    'meta_value'   =>  '1', //  use 0 for unchecked state
);
$user_query = new WP_User_Query($args);

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

Note: The code provided searches for items with a saved value of '1' (true). If you need to find items that have either a value of '0' (false) or no value at all, use the following snippet:

$args = array(
    'meta_query' => array(
        'relation' => 'OR', // Combine multiple meta queries
        array(
            'key'     => 'your_true_false_field', // Replace with your field name
            'value'   => '0', 
        ),
        array(
            'key'     => 'your_true_false_field', // Replace with your field name
            'compare' => 'NOT EXISTS' // Include users where the field does not exist
        )
    )
);

$user_query = new WP_User_Query($args);

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

5.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.

6. Related True/False 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 True/False field type:

6.1) acf/load_field

The acf/load_field filter allows you to modify the field settings before it is displayed on the editor's screen. This filter is particularly useful for dynamically adjusting the field's configuration, such as setting default values, changing labels, or customizing available options.

add_filter('acf/load_field/name=my_true_false_field', function (array $field): array {
    // Modify the field settings as needed
    $field['instructions'] = 'Please select true or false.';
    $field['message'] = 'This is a custom message for the True/False field.';

    return $field;
});

6.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.

add_action('acf/render_field/name=my_true_false_field', function (array $field): void {
    // 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.

6.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 meets specific criteria:

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

	// todo Custom validation
	if ( false === my_custom_value_validation( $value ) ) {
		return 'The value is invalid.';
	}

	return $valid;
}, 10, 3 );

6.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.

add_action('acf/validate_save_post', function () {
    // Get the True/False field values from ACF fields
    $true_false_1 = $_POST['acf']['field_true_false_key_1'] ?? '';
    $true_false_2 = $_POST['acf']['field_true_false_key_2'] ?? '';

    if ($true_false_1 !== '1' && $true_false_2 !== '1') {
        acf_add_validation_error('field_true_false_key_1', 'At least one True/False field must be checked.');
        acf_add_validation_error('field_true_false_key_2', 'At least one True/False field must be checked.');
    }
});

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.

6.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, e.g. updating related data.

add_action('acf/save_post', function ($post_id) {
    // Retrieve the True/False field value (replace with your actual True/False field key)
    $true_false_value = get_field('my_true_false_field', $post_id);

    if (!$true_false_value) {
        return;
    }

    // Retrieve the related post ID (replace with your actual relationship field key)
    $related_post_id = get_field('related_post', $post_id);

    if (!$related_post_id) {
        return;
    }

    // Get the current value of the 'related_item' field in the related post
    $related_items = get_field('related_item', $related_post_id);

    if (!is_array($related_items)) {
        $related_items = [];
    }

    // Add the current post ID to the 'related_item' field
    if (!in_array($post_id, $related_items)) {
        $related_items[] = $post_id;
        update_field('related_item', $related_items, $related_post_id);
    }
});

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 I update an ACF True/False field programmatically?

    Yes, you can update a True/False field programmatically using the ACF update_field() function. When doing so, make sure to pass boolean values (true or false) rather than '1' or '0'.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Related articles

Content links (54)

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