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

0

Days

:

0

Hrs

:

0

Mins

:

0

Secs

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

ACF User Field: Complete Guide with Code Snippets

Explore ACF User field: set up custom user-content relationships, filter by role, use bidirectional sync, and display user details in grids or sliders.

Key Points at a Glance

  1. Field Overview: The ACF User field allows linking users to content by storing their IDs in object metadata.
  2. Field settings: Includes options for filtering users by role, choosing return formats, enabling multiple selections, and creating bidirectional relationships.
  3. Storage Format: User ID are stored as a numeric string or serialized array, depending on the 'Select Multiple' setting.
  4. Bidirectional Feature: The User field supports bidirectional relationships, synchronizing related fields automatically between content and user metadata.
  5. Loading field values: Use Advanced Views Framework or custom code to display user details as links or grids, with options for styling and layout.
  6. Querying related content: Use WP_Query or Advanced Views Framework to retrieve posts or content related to selected users.

Table of Contents

The ACF User field, part of the Relational field group in the Advanced Custom Fields plugin, enables editors to select users and associate them with specific content by storing their IDs in the object metadata.

This functionality allows for more flexible and dynamic user associations beyond the default options provided by WordPress.

Note: While WordPress includes a built-in 'author' field for pages, posts, custom post types, and attachments - allowing authorship to be assigned and changed at any time - the ACF User field extends these capabilities. It offers the ability to link one or multiple users to content in more customized ways, such as designating ‘product managers’ for products or 'magazine editors' for Magazines CPT.

ACF User field UI

General settings of the ACF User field.
Bidirectional setting of the ACF User field
The User field supports the Bidirectional feature, which keeps related fields in sync automatically.
ACF User field look for editors
The field displays a select-like appearance for editors, including user roles for easy identification

ACF User field-related addons

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

  • ACF to Custom Database Tables is an add-on for Advanced Custom Fields that saves your custom field data in a dedicated, structured database table, improving organization and performance.
  • 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.

User fields in other meta-field plugins

If you're considering alternatives to ACF, similar functionality can be found in other popular meta-field plugins. The Meta Box plugin offers the MB User field, while Pods provides this feature through its universal relationship field - the Pods Relationship field.

For a detailed comparison of these options, be sure to check out our comprehensive guide on the best meta-field plugins. This guide breaks down the key differences, helping you choose the right tool for your project.

1. ACF User field essentials

1.1) Field settings

Beyond the standard settings like field name and label, the ACF User field offers specific options:

General tab

  1. Filter by Role:
    Restrict the users displayed in the field to specific roles, like administrators, editors, or subscribers, making it easier to find the right user.
  2. Return Format:
    Controls how the selected user data is returned - either as a user array, user object, or just the user ID.
  3. Select Multiple:
    Enable or disable the selection of multiple users, allowing you to associate more than one user with the content.

Validation tab

  1. Allow Null:
    Permits editors to 'reset' the chosen user, which is necessary for optional user associations.

Advanced tab

  1. Bidirectional:
    Create two-way relationships between content and user fields, ensuring that if a user is linked to a post meta, the post is also linked back to the user meta, keeping data connections consistent. We'll review this feature in detail.

1.2) Storage format and supported field locations

The ACF User field stores the selected user IDs in the object metadata. The format of this data depends on the field's settings. When the "Select Multiple" setting is disabled, the field stores the chosen user ID as a numeric string:

The chosen user is stored as a numeric ID.

When the "Select Multiple" setting is enabled, the field stores the user IDs as a serialized array. For instance, if three users with IDs 5, 12, and 27 are selected, the data would be stored as:

a:3:{i:0;s:1:"5";i:1;s:2:"12";i:2;s:2:"27";}

Supported field locations

The ACF User field is versatile, allowing user associations across different contexts, and it consistently stores values depending on where the field is applied:

  1. Post Objects (Post, Page, Media Attachment, Custom Post Type, WooCommerce Product):
    The User field can be attached to any post type, including pages, media attachments, and custom post types, all stored in the wp_posts table. The selected user IDs are saved in the wp_postmeta table, linked to the relevant post or custom post type item.
  2. Options Page:
    On an ACF Options Page, the User field can store its data in the wp_options table. This setup is ideal for global user settings.
  3. User Profiles:
    When used in user profiles, the User field stores selected user IDs in the wp_usermeta table, associated with the respective user. This application is particularly useful for linking users to mentors, managers, or any custom relationship directly within user profiles.
  4. Terms (e.g., Post Categories):
    The User field can be applied to taxonomy terms like categories, tags, or custom taxonomies. In this scenario, the user IDs are stored in the wp_termmeta table, connected to the specific term, making it possible to assign users to categories, such as designating a 'category manager.'
  5. ACF Gutenberg Block:
    When used within custom ACF blocks, the User field's values are embedded within the block's JSON data structure in the post_content column of the wp_posts table.

1.3) Return value formats

The Return Value setting determines how the selected user(s) are returned when using the ACF get_field() function.

This choice impacts the user (item) presentation. If you’ve chosen the 'Select Multiple' option, the response will always be an array, and this setting controls the format of each item within that array. Here’s a breakdown of the options:

  1. User Array (default):
    Returns an associative array of user data, including details like the user’s ID, display name, email, and other metadata fields. This option provides a lightweight, structured view of the user information, making it easy to access specific attributes.
  2. User Object:
    Returns the complete WP_User object, offering full access to all user properties and methods. This option is ideal when you need in-depth interaction with the user data.
  3. User ID:
    Returns just the user’s ID as an integer. This minimal approach is perfect when you only need the user ID for further queries or to pass into other functions.

Array keys:

$response = [
    'ID'                => 12,                     // int
    'user_firstname'    => 'John',                 // string
    'user_lastname'     => 'Doe',                  // string
    'nickname'          => 'johndoe',              // string
    'user_nicename'     => 'john-doe',             // string
    'display_name'      => 'John Doe',             // string
    'user_email'        => '[email protected]',     // string
    'user_url'          => 'https://example.com',  // string
    'user_registered'   => '2024-01-15 10:30:00',  // string
    'user_description'  => 'A brief user bio.',    // string
    'user_avatar'       => 'https://example.com/avatar.jpg', // string
];

2. Bidirectional User field feature

The ACF User field supports the bidirectional feature, automating the updating of fields on related objects. This eliminates the need for manual queries and simplifies the use of field values, especially for beginners.

With the bidirectional setting enabled for the ACF User field, related fields are automatically kept up-to-date.

Bidirectional setting of the ACF User field
To set up the bidirectional feature, navigate to the Advanced tab.

Let's illustrate this with an example involving Company CPTs. A company can have multiple employees (WordPress users), represented by an 'Employees' User field in the Company CPT. This setup is relatively straightforward.

Now, let's dive into the task at hand. Our goal is to retrieve a list of all companies where the current user is associated. With the introduction of the Bidirectional feature, we can achieve this without creating a custom query. Here's how:

  1. Create a new Post Object field:
    Add a new Post Object or Relationship field, perhaps named 'Companies', and attach it to the user account's screen.
  2. Enable the Bidirectional feature:
    Navigate to the 'Employees' User field and enable the Bidirectional feature. Set the target field as the new 'Companies' field.

Once these steps are completed, ACF will automatically track changes. When you update the 'Employees' User field, ACF will automatically update the related company in the associated user's 'Companies' field.

This approach ensures that you always obtain an up-to-date list of the companies associated with each user, just like the value of the original Post Object field.

Pro tip: You can further enhance this setup by enabling the Bidirectional feature for the 'Companies' Post Object field as well. This way, any additions or removals of companies on the user's side will be automatically reflected on the company's side too.

In this manner, you can establish bidirectional relations between different items.

Apart from the CPT-to-user case described above, you can also set up a user-to-user relationship. For instance, WordPress users with the 'boss' role may have the 'employees' user field, while WordPress users with the 'employee' role may have the 'boss' user field.

3. Use cases of the ACF User field

The ACF User field offers versatile applications across various scenarios, enhancing content relationships and user management. Here are some common use cases:

3.1) Assigning custom roles to content

The ACF User field allows you to assign custom roles to content beyond the standard author. For instance, you can link specific users as "Product Managers" for WooCommerce products, "Editors" for blog posts, or "Contributors" for specific custom post types. This is particularly useful in multi-author blogs, publications, or complex content workflows.

3.2) Creating custom user associations in profiles

Adding the User field to user profiles enables the creation of custom connections between users. For example, you can set up mentor-mentee relationships, designate managers to team members, or link users to specific projects. This setup helps build dynamic relationships within the user data, enhancing how users interact and relate to each other.

3.3) Managing access to content or features

The ACF User field can help manage content access by linking specific users to certain content or features. For instance, you might restrict access to premium content by assigning users with certain roles, or you can use it to set user-specific permissions, such as assigning editors to specific categories.

3.4) Selecting responsible users for site-wide features

On ACF Options Pages, the User field can be used to select users responsible for certain site-wide tasks, like site administrators, support contacts, or featured content curators. This approach centralizes control and easily reflects changes without editing multiple settings.

3.5) Enhancing user-specific content

For membership sites or community-driven platforms, the User field can be used to show user-specific content, like assigning personalized messages, highlighting specific content authored or edited by a user, or showcasing a "Featured Author" section.

3.6) User management for Events or Projects

The ACF User field can be used in event management or project-based websites to assign users as event organizers, speakers, or project owners. This setup makes it simple to manage and display user roles within these contexts directly on the front end.

4. ACF User 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 User fields:

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

5. Code snippets for the ACF User 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 the field value

Using Advanced Views Framework

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

When using the ACF User field without the 'Select Multiple' option, by default the template renders a single clickable username. For fields with 'Select Multiple' enabled, the template iterates over each selected user, displaying them as individual links.

If it needs, you can add CSS rules to the CSS field of your View, to get the desired look.

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

In the AVF Pro edition, you can define a separate View for the User item, which will control the user display. This setup allows you to load and display any extra user fields, including custom fields, such as using an ACF image field as a user avatar.

Using custom code

The ACF get_field function response will differ based on the chosen return format. The User Array is the default option. The get_field() function loads the value from the current object (page/post), and in case you need to load from the other source, pass it as a second argument, as shown in the code snippet:

// Replace 'user_field' with the name of your ACF User Field
$selected_user = get_field('user_field'); // from the current post
$selected_user = get_field('user_field', 10); // from a specific post by ID
$selected_user = get_field('user_field', 'option'); // from the options page
$selected_user = get_field('user_field', 'user_1'); // from the user by ID
$selected_user = get_field('user_field', 'category_2'); // from the category term with ID 2
$selected_user = get_field('user_field', 'genre_3'); // from the custom genre term with ID 3

The code should be added to the target template of your theme. In most scenarios, the first step is to extract the user ID:

// optionally: loop through the values if the 'multiple' option is enabled
// foreach($selected_users as $selected_user){

    // Getting user ID from the array response
    $user_id = $selected_user['ID'];

    // Getting user ID from the object response
    $user_id = $selected_user->ID;

    // Getting user ID from the 'id' response
    $user_id = $selected_user;

// }

After retrieving the user ID, the next step is to generate the proper markup (see the examples below). For layout styling, assign specific classes and add corresponding CSS rules. While you can include these styles in your theme's style.css file, it's better to add them to a template-specific CSS asset (if your theme supports it) to prevent the styles from affecting the entire site.

5.2) Displaying the chosen user as a link

One of the most straightforward and common uses of the ACF User field is to display selected users as clickable usernames (using the HTML anchor element), leading directly to their author pages.

Using Advanced Views Framework

The framework automatically loads the field value along with the default template. Since the link display is set as the default option, you can keep the auto-generated template unchanged:

Single User (without 'Select Multiple'):

{% if user.value %}
    <a target="{{ user.target }}" href="{{ user.value }}">
        {{ user.linkLabel|default(user.title) }}
    </a>
{% endif %}

Multiple Users (with 'Select Multiple'):

{% if user_multiple.value %}
    <div>
        {% for user_item in user_multiple.value %}
            <a target="{{ user_item.target }}" href="{{ user_item.value }}">
                {{ user_item.linkLabel|default(user_item.title) }}
            </a>
        {% endfor %}
    </div>
{% endif %}

Using custom theme code

To get the author page URL, and user display name, we'll use the get_author_posts_url() and get_the_author_meta() WordPress functions. Don't forget about security, and escape the output data as shown below:

Single User (without 'Select Multiple'):

$user_id = get_field('user_field')['ID'] ?? 0;

if ($user_id) {
    // Generate a link to the user's author page
    printf(
        '<a href="%s">%s</a>',
        esc_url(get_author_posts_url($user_id)),
        esc_html(get_the_author_meta('display_name', $user_id))
    );
}

Multiple Users (with 'Select Multiple'):

$selected_users = get_field('user_field'); // Assuming this returns an array of users

if ($selected_users) {
    foreach ($selected_users as $user_item) {
        // Extract the user ID based on the return format
        $user_id = $user_item['ID'];

            // Generate a link to the user's author page
            printf(
                '<a href="%s">%s</a>',
                esc_url(get_author_posts_url($user_id)),
                esc_html(get_the_author_meta('display_name', $user_id))
            );
    }
}

5.3) Displaying user details in a list or grid

Displaying a simple user link is minimalist, but in many cases, you may want to show more details about the selected user(s). For example, besides the user’s name, you might also want to display their bio, website, and avatar, with the avatar being an ACF Image field attached to the user.

Users grid
Users are displayed with their details.

Using Advanced Views Framework

To display user details, follow the steps, described in the AVF User field Docs:

  1. Use the AVF Pro Edition: Ensure you have the AVF Pro edition, which allows you to customize the appearance of object fields.
  2. Create the Primary View: Start by creating the main View, which will act as the master View. Choose the target user field and save the View.
  3. Create a ‘User Details’ View: This View will be responsible for displaying user details. In the Fields tab, select the user fields you want to display, such as the display name, bio, website, and avatar (an ACF Image field).
  4. Save the 'User Details' View: After setting up the fields, save the 'User Details' View.
  5. Link the Views: Go back to the primary (master) View. In the User field settings, select the 'User Details' View in the 'View' setting.
  6. Save the Master View: Save the master View to complete the setup.
  7. Customize as Needed: Now, each chosen user in the User field will be displayed according to the 'User Details' View. You can further customize the markup and add CSS styles as needed.

That's it! By following these steps, you can display detailed user information and have full control over the layout and styling.

To display all the items in a single row, you can use the CSS Flexbox:

#view__users {
display: flex;
gap: 10px;
}

To display all the items as a grid, you can use the CSS Grid:

#view__users {
 display: grid;
 grid-template-columns: 1fr;
 gap: 20px;
 }

@media screen and (min-width:992px) {
 #view__users {
  grid-template-columns: repeat(4, 1fr);
 }
}

Using custom code

In this example, we use the get_the_author_meta function to fetch user data like the display name, bio, and website, and the get_field function to load the avatar, which is set up as an ACF Image field.

To render the avatar, we utilize the wp_get_attachment_image function, which generates the proper image tag with attributes. Don't forget about security, and escape the output data as shown below:

The code includes a loop to handle multiple users; if you're working with a single-user response, simply remove the loop and adjust the variables accordingly.

$selected_users = get_field( 'user_field' ); // Replace 'user_field' with your actual field name

if ( $selected_users ) {
        echo '<div class="users">';
	foreach ( $selected_users as $user_item ) {
		// Extract the user ID based on the response format
		$user_id = $user_item['ID'];

		// Get user details
		$display_name    = get_the_author_meta( 'display_name', $user_id );
		$bio             = get_the_author_meta( 'description', $user_id );
		$website         = get_the_author_meta( 'user_url', $user_id );
		$avatar_image_id = get_field( 'user_avatar',
			'user_' . $user_id )['ID'] ?? 0; // Replace 'user_avatar' with your ACF Image field name

		// Generate user avatar markup if it exists
		$avatar_img = $avatar_image_id ?
			wp_get_attachment_image( $avatar_image_id, 'medium' ) :
			'';

		// Generate user details markup
		printf(
			'<div class="user-details">
                    %s
                    <h3 class="user-name">%s</h3>
                    <p class="user-bio">%s</p>
                    <a href="%s" target="_blank" class="user-website">%s</a>
                </div>',
			$avatar_img,
			esc_html( $display_name ),
			esc_html( $bio ),
			esc_url( $website ),
			esc_html( $website )
		);
	}
       echo '</div>';
}

To display all the items in a single row, you can use the CSS Flexbox:

.users {
display: flex;
gap: 10px;
}

To display all the items as a grid, you can use the CSS Grid:

.users {
 display: grid;
 grid-template-columns: 1fr;
 gap: 20px;
 }

@media screen and (min-width:992px) {
 .users {
  grid-template-columns: repeat(4, 1fr);
 }
}

5.4) Displaying users in a slider

Another great way to showcase the user details is to display them in a slider. We can display one item at a time, or opt for multiple at once, as well as enable the auto slide option.

Splide slider
The horizontal slider allows you to showcase one or multiple items at a time and smoothly scroll to the next set of items.

The first thing to do is to select the target slider library. In this article, we've opted for Splide, which is a well-known library with rich options and excellent performance.

The simplest way to turn the repeater into the slider is to use AVF Pro edition, as the framework comes with pre-configured Slider, Masonry, and Image gallery libraries.

Using Advanced Views Framework

After adding the user field with the 'multiple' option enabled to the target View, change the 'Enable Slider' option to 'Splide v4' and press the Save button, as described on the AVF User Docs page. The framework will automatically change the field markup to incorporate the necessary classes, and add the default JS instance:

var users_field = this.querySelector('.acf-view__users');
if (users_field) {
	/* https://splidejs.com/guides/options/ */
	new Splide(users_field, {
		type: 'loop',
		perPage: 1,
		perMove: 1,
	}).mount();
}

Now you can customize the settings according to your needs, using any available Splide options.

Using custom code

In this case, you need to download the CSS and JS code of the Splide library to your theme. Then, print the relationship items in the target template with the necessary splide classes:

$selected_users = get_field('user_field'); // Replace 'user_field' with your actual field name

if ($selected_users) {
    echo '<div class="splide"><div class="splide__track"><ul class="splide__list">';
    foreach ($selected_users as $user_item) {
        // Extract the user ID based on the response format
        $user_id = $user_item['ID'];

        // Get user details
        $display_name    = get_the_author_meta('display_name', $user_id);
        $bio             = get_the_author_meta('description', $user_id);
        $website         = get_the_author_meta('user_url', $user_id);
        $avatar_image_id = get_field('user_avatar', 'user_' . $user_id)['ID'] ?? 0; // Replace 'user_avatar' with your ACF Image field name

        // Generate user avatar markup if it exists
        $avatar_img = $avatar_image_id ? wp_get_attachment_image($avatar_image_id, 'medium') : '';

        // Generate user details markup
        printf(
            '<li class="splide__slide">
                <div class="user-details">
                    %s
                    <h3 class="user-name">%s</h3>
                    <p class="user-bio">%s</p>
                    <a href="%s" target="_blank" class="user-website">%s</a>
                </div>
            </li>',
            $avatar_img,
            esc_html($display_name),
            esc_html($bio),
            esc_url($website),
            esc_html($website)
        );
    }
    echo '</ul></div></div>';
}

Then enqueue the library's CSS using the wp_enqueue_style function, and add the following JS to your theme's script.js:

import '/wp-content/themes/YOUR_THEME/assets/js/splide.js';

document.addEventListener('DOMContentLoaded', function () {
    var slider = document.body.querySelector('.splide');
    if (slider) {
        /* https://splidejs.com/guides/options/ */
        new Splide(slider, {
            type: 'loop',
            perPage: 1,
            perMove: 1,
        }).mount();
    }
});

Now you can customize the settings according to your needs, using any available Splide options.

5.5) Updating the user field programmatically

To update the User field programmatically, you can use the ACF update_field function. Since this field always stores the user ID, the value you pass must be a valid user ID.

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

add_action('acf/init', function() {
    // for user fields without the multiple option, pass the integer ID
    update_field('my_user_field', 10, 1); //replace 10 with the target user ID and 1 with the target post ID

     // for user fields with the multiple option, pass the integer IDs array
    update_field('my_user_field', [10,], 1); //replace 10 with the target user ID and 1 with the target post ID
});

If you need to update the User 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 User field

Beyond displaying user details, you might also want to show posts (or products) related to the chosen user. There are two common scenarios: retrieving posts created by the user (using the default WordPress author field) and finding related posts where the chosen user is selected in some ACF User field.

For posts related to an ACF field, you can streamline the process by using the bidirectional feature, as discussed earlier, which eliminates the need for manual queries.

Here's how to handle queries depending on where the User field values are stored:

6.1) By the author field

To find posts, authored by the chosen user, you need to use the author argument of the WP_Query:

$args = array(
    'post_type' => 'post', // Replace with your custom post type if needed
    'post_status' => 'publish',
    'posts_per_page' => -1, // Retrieve all posts
    'author' => get_field('user_field')['ID']??0, // change the field name to yours
);

// Execute the query
$query = new WP_Query($args);

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

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

To find items, where the target user is chosen in a specific field, you need to use the meta_query feature of the WP_Query class. In case the target User field supports multiple items, you should use the Like comparison, instead of the default (equal).

Using Advanced Views Framework:

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

Choose the "Contains" comparison if the "multiple" option is enabled for the field; otherwise, leave it set to "Equal." Save the Card and insert the shortcode into the desired location on your site. That’s it! The framework will handle the query automatically and display the related posts accordingly.

Using WP_Query:

We need to employ the WP_Query class:

$args = array(
    'post_type' => 'post', // Replace with your custom post type if needed
    'post_status' => 'publish',
    'posts_per_page' => -1, // Retrieve all posts
    'meta_query' => array(
        array(
            'key'     => 'your_user_field', // Replace with your ACF User field key
            'value'   => '10',  // user id
        )
    )
);

// Execute the query
$query = new WP_Query($args);

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

In case you've enabled 'multiple' items option in the field, use the 'LIKE' comparison as shown below:

$args = array(
    'post_type' => 'post', // Replace with your custom post type if needed
    'post_status' => 'publish',
    'posts_per_page' => -1, // Retrieve all posts
    'meta_query' => array(
        array(
            'key'     => 'your_user_field', // Replace with your ACF User field key
            'value'   => '"10"', // to match the serialized data
           'compare' => 'LIKE', // to match the serialized data
        )
    )
);

// Execute the query
$query = new WP_Query($args);

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

6.3) By termmeta (Terms)

Here we need to employ the WP_Term_Query class.

For the user field without the multiple option:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'your_user_field', // Replace with your ACF User field key
            'value'   => '10', // Target user ID 
        )
    )
);

// Execute the query
$term_query = new WP_Term_Query($args);

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

For the user field with the multiple option:

$args = array(
    'taxonomy'   => 'category', // Replace with your taxonomy
    'meta_query' => array(
        array(
            'key'     => 'your_user_field', // Replace with your ACF User field key
            'value'   => '"10"', // to match the serialized data
            'compare' => 'LIKE', // to match the serialized data
        )
    )
);

// Execute the query
$term_query = new WP_Term_Query($args);

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

6.4) By usermeta (user profile)

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

For the user field without the multiple option:

$args = array(
    'meta_query' => array(
        array(
            'key'     => 'your_user_field', // Replace with your ACF User field key
            'value'   => '10', // Target user id
        )
    )
);

$user_query = new WP_User_Query($args);

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

For the user field with the enabled multiple option:

$args = array(
    'meta_query' => array(
        array(
            'key'     => 'your_user_field', // Replace with your ACF User field key
            'value'   => '"10"', // Target post ID wrapped in double quotes to match serialized data
            'compare' => 'LIKE', // to match the serialized data
        )
    )
);

$user_query = new WP_User_Query($args);

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

6.5) 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 User 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 User field type:

7.1) acf/load_field

The load_field filter allows you to modify the field settings before it is displayed. You can use it to filter the user's list. For example, if you want to show only users with a specific meta value:

add_filter('acf/load_field/name=my_user_field', function(array $field):array {
    // Modify query to filter users based on custom meta field
    $field['choices'] = wp_list_pluck(
        get_users(['meta_key' => 'custom_meta_key', 'meta_value' => 'desired_value']),
        'display_name',
        'ID'
    );

    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 validate_value filter to validate the values entered into the field. You can ensure that the selected users meet specific criteria:

add_filter('acf/validate_value/name=my_user_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 === validate_user_id($value)) {
        $valid = 'Invalid user 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.

add_action( 'acf/validate_save_post', function () {
	// Get values from the fields
	$user_id = $_POST['acf']['field_123456789abc'] ?? ''; // Replace with your User Field key
	$role    = $_POST['acf']['field_abcdef123456'] ?? '';    // Replace with your Role Field key

	// Fetch the selected user's data
	$user = get_userdata( $user_id );

	// Check if the user's role matches the selected role
	if ( false !== $user &&
	     false === in_array( $role, $user->roles, true ) ) {
		// Replace with your User Field key
		acf_add_validation_error( 'field_123456789abc', 'The selected user does not match the specified role.' );
	}
} );

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 save_post action is triggered when a post or user field is saved. You can use it to perform any additional actions, e.g. sending an email:

add_action( 'acf/save_post', function ( $post_id ) {
	$my_user_field = get_field( 'my_user_field', $post_id );

	if ( ! $my_user_field ) {
		return;
	}

	$user_id    = $my_user_field['ID']; // Adjust based on the field's return format
	$user_email = get_the_author_meta( 'user_email', $user_id );
	$user_name  = get_the_author_meta( 'display_name', $user_id );

	// Prepare the email content
	$subject = "You've been selected!";
	$message = "Hello {$user_name},\n\nYou have been assigned a new task.";

	// Send an email to the selected user
	wp_mail( $user_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. Do "User field" and "user fields" mean different things?

    Yes, they do. Despite sounding similar, they refer to different concepts. The ACF User field is a specific field type within Advanced Custom Fields that allows you to select a user from your WordPress site. On the other hand, "user fields" generally refer to the custom fields you add to a user profile using ACF.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

Related articles

Content links (89)

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