WPLake > Learning Hub > ACF Relationship Field

ACF Relationship Field

Enhance content relationships with the ACF Relationship field: Versatile connections, bidirectional linking, advanced filtering, and customizable display.

Key Points at a Glance

  1. ACF Relationship Field Purpose: The ACF Relationship field establishes connections between various post types or custom post types, facilitating the creation of meaningful relationships between different content elements.
  2. Flexibility of ACF Relationship Field: Users can choose between single and multiple selections, allowing them to connect one post or page to several related items, catering to diverse scenarios from simple one-to-one connections to complex one-to-many relationships.
  3. Comparison with Post Object Field: While similar, the ACF Relationship field offers more advanced filtering options and bidirectional linking, making it ideal for scenarios involving many-to-many relationships and interconnected content.
  4. Querying with WP_Query: Utilizing the WP_Query function, users can retrieve content based on established relationships, leveraging the meta_query parameter to filter posts by their post meta values.
  5. Bidirectional Feature: Introduced in version 6.2, the bidirectional feature allows for automatic updating of related fields, eliminating the need for custom WP_Query instances and simplifying the display of related content.
  6. Displaying Relationships: Users have the option to display related content using smart templates provided by plugins like Advanced Views or manually through code, offering flexibility and customization options based on individual preferences.

Table of Contents

About the Relationship field

The ACF Relationship field is one of the field types provided by the Advanced Custom Fields plugin, which is one of the best plugins for managing meta fields and Custom Post Types (CPTs).

It serves as a powerful bridge, forging connections between various post types, pages, or custom post types. This unique ability allows content creators to establish meaningful relationships between different content elements.

Imagine a portfolio website where artists and their artworks are managed separately. By utilizing the Relationship field, you can effortlessly link the artworks to their respective creations, showcasing a seamless connection between the two. Or use the ACF relationship field with a WooCommerce product, if it needs to be related to a certain company or manager.

ACF Relationship field. Editors can easily find and attach the target posts using the search input and filters.
Editors can easily find and attach the target posts using the search input and filters.

One of the features of the ACF Relationship field that stand out is its remarkable flexibility in linking content. Users have the liberty to choose between single and multiple selections, enabling them to connect a post or page to one or more related items. This adaptability is invaluable, catering to a wide range of scenarios, from straightforward one-to-one connections to intricate one-to-many relationships.

Field settings of the ACF Relationship field include Filters by Post Type, Post Status, and Taxonomy.
Field settings of the ACF Relationship include Filters by Post Type, Post Status, and Taxonomy.

To keep content organized and presented cohesively, the ACF Relationship field offers ordering and filtering options. By changing the order in the relationship select area, using drag and drop, you can arrange the selected content in a logical order, ensuring a consistent display throughout your website. Additionally, the filtering capability empowers you to narrow down available options, simplifying the process of finding and linking related content.

Note: The ACF Relationship field isn't suited for use with Taxonomies. So if you're planning to associate a Taxonomy then use the Taxonomy field instead.

Relationship vs Post Object

The Advanced Custom Fields plugin offers two powerful field types to establish relationships between different content items: the Relationship field and the Post Object field. While both fields serve similar purposes, they have distinct characteristics that cater to different use cases. In this chapter, we will explore the differences between these two field types to help you decide which one best suits your needs.

Relationship field

The Relationship field is specifically designed to create associations between posts of different post types. It allows you to establish many-to-many relationships, meaning a single post can be linked to multiple related posts, and vice versa. This field is perfect for scenarios where you want to showcase related content, create custom post relationships, or build a network of interconnected content.

Key Features of the Relationship Field:

  • Many-to-many relationships between different post types.
  • Enables bidirectional linking of posts.
  • Perfect for building custom post relationships and interconnected content.
  • Provides an intuitive interface to search, select, and order related posts.

Post Object Field

On the other hand, the Post Object field serves similar needs but provides a more simple interface, without the filters. It may be useful if you don't want to provide filtering options for editors. In addition, by default, the field allows us to choose only a single item. So it's similar to a traditional "foreign key" concept in databases.

The ACF Post Object field looks like a select. Only the search box by post titles is available for filtering.
The Post Object field looks like a select. Only the search box by post titles is available for filtering.

Key Features of the Post Object Field:

  • Simple UI
  • No filters for editors
  • Better suited for a single relationship

Choosing the Right Field Type

The decision to use either the Relationship field or the Post Object field depends on the nature of your content and the specific requirements of your project.

Use the Relationship field when:

  • You need to create many-to-many relationships between different post types.
  • Your content structure involves interconnected or related posts that need bidirectional linking.
  • You want a user-friendly interface to easily search, select, and manage related posts.

Use the Post Object field when:

  • You only need to associate a single post with another post, page, or custom post type.
  • The relationships between your content items are more straightforward and do not require bidirectional linking.

In conclusion, both the Relationship field and the Post Object field are powerful tools to establish relationships between content items in WordPress. By understanding their differences and knowing your specific project requirements, you can confidently choose the field type that best fits your needs and create a seamless and efficient content management experience.

Behind the scenes

Storing Relationships in the Database

When you create a Relationship field and establish connections between content elements, ACF handles the storage of these relationships intelligently. Instead of directly linking content in the database, ACF utilizes post meta to store the relationships discreetly. Each post or page that contains a Relationship field stores the related content elements' IDs as post meta.

For instance, imagine you have a "Team" post type and a "Project" post type, each with a unique set of data. By using the Relationship field, you can link specific team members to their associated projects. Behind the scenes, ACF stores the team members' IDs as post meta within the "Project" post, creating a seamless connection without altering the original content.

Query with WP_Query

With the relationships discreetly stored as post meta, the true power of the ACF Relationship field becomes evident when utilizing WP_Query. WP_Query is a core WordPress function that allows you to query the database for specific posts based on various parameters.

To leverage the relationships created with the ACF Relationship field, you can utilize the meta_query parameter in WP_Query. This parameter enables you to query posts based on their post meta values, making it possible to retrieve content based on the established relationships.

Continuing from our earlier example, let's say you want to display all projects associated with a specific team member. By constructing a custom WP_Query with the appropriate 'meta_query' parameters, you can easily retrieve the desired projects linked to the team member's ID.

You can see examples in the 'Query by Relationship field' chapter of this article.

Query with the Bidirectional feature

Starting from version 6.2, you have the option to use the Bidirectional feature as an alternative to creating custom WP_Query instances. This feature enables you to retrieve related posts using the familiar approach of get_field. For further details, you can refer to the 'Query by Relationship Field' chapter of this article.

Display Relationship field

Display using Smart templates

Let's get familiar with a new tool, called Advanced Views.

Advanced Views framework introduces smart templates for effortless content display. It comes with built-in post queries and automated template generation, enabling rapid development while maintaining flexibility.

Let's first clarify what we mean by 'templates' in the context of this plugin: Advanced Views templates are built on the Twig engine. You might be thinking, 'Not bad, but it still requires fetching fields via PHP and writing markup from scratch, not to mention reading Twig documentation'.

Here's where the plugin shines: "Smart templates". This means we don't have to fetch fields or create markup manually from scratch. The plugin provides a solid foundation that covers most use cases. If we require something specific, we can easily customize it. Isn't that nice?

Basics

Now, let's take a basic look at how it works.

The plugin introduces two new Custom Post Types (CPTs): ACF View and ACF Card.

  • View for post data and Advanced Custom Fields
    We create a View and assign one or more post fields, the plugin then generates a shortcode that we'll use to display the field values to users. We can style the output with the CSS field included in every View.
  • Card for post selections
    We create a Card and assign posts (or CPT items), choose a View (that will be used to display each item) and the plugin generates a shortcode that we'll use to display the set of posts. The list of posts can be assigned manually or dynamically with filters.

The plugin offers us the convenience of working with familiar WordPress CPTs while taking care of querying and automatically generating Twig markup templates. You can find more information about the plugin's benefits here.

To follow along; install the Advanced Views framework on your WordPress site and remember to activate it. You'll also need the ACF (free) plugin installed and active. Then continue to the next steps below.

Tip: Basic vs Pro
With the Basic version of Advanced Views support all the field types, and displays the items of relationship field as post links. Which makes it a convenient option for users seeking a straightforward solution. However, for those who wish to customize the display and explore various layout options, the Pro version is for you, and it allows you to display any post or meta fields of the related items.

Step-by-step guide

Below is a step-by-step guide that will help you create an ACF View:

  1. Install and Activate the Advanced Views framework
    Head over to your WordPress dashboard, navigate to "Plugins," and click on "Add New." Search for "Advanced Views" and install the plugin. Once installed, activate it to enable its functionality.
  2. Create a View
    Upon activation, you'll find a new menu item called "Advanced Views" in your admin menu. Click on it, and then click "Add New" to create a View.
  3. Assign Fields to the View
    Within the View creation screen, you can assign multiple fields, including your Relationship Field, for display. Choose your "Group" from the dropdown, select the Relationship Field from the list, and proceed.
    Note: Using the Advanced Views Pro version, you can also define a custom View for the items, and display extra fields, like Featured Image or any ACF field.
  4. Publish the View
    Click on the "Publish" button to save and publish your View.
  5. Retrieve the Shortcode
    Once the View is published, Advanced Views generates a shortcode with a unique ID for your View. Copy the shortcode to use it in your desired post or page.
  6. Display Related Content
    Paste the shortcode into the post or page where you want to display the related content. The plugin will handle the rest, showcasing your connected content in a user-friendly and customizable manner.
Example of displaying the Relationship field using ACF Views. ACF Views (Basic) automatically displays the items of the relationship field as post links.
Example usage. Advanced Views automatically displays the items of the relationship field as post links.
Example of displaying the Relationship field using ACF Views Pro. The plugin allows the creation of custom layouts. Choose the target post and meta fields, and the plugin will automatically display them.
Example usage. Advanced Views Pro allows the creation of custom layouts. Choose the target post and meta fields, and the plugin will automatically display them.

With these straightforward steps, the Advanced Views framework provides a simple yet powerful solution to display and customize the content from your ACF Relationship Field. Embrace the flexibility and convenience of Advanced Views, and create captivating and interactive content displays without the need for manual coding.

Display using code

Besides using smart templates, you can display the fields in a classic manner, manually. Below, we have provided an example.

// Replace 'relationship_field' with the name of your Relationship Field
$related_items = get_field('relationship_field');

if ($related_items) {
    foreach ($related_items as $related_item_id) {
        $related_post = get_post($related_item_id);

        if (!$related_post) {
            // Skip this iteration if the related post is not found
            continue;
        }

        printf('<div class="related-item">');

        // Display featured image if available
        if (has_post_thumbnail($related_item_id)) {
            printf('<div class="related-item__image"><a href="%s">%s</a></div>', esc_url(get_permalink($related_item_id)), get_the_post_thumbnail($related_item_id, 'thumbnail'));
        }

        // Display post title
        printf('<h2 class="related-item__title"><a href="%s">%s</a></h2>', esc_url(get_permalink($related_item_id)), esc_html($related_post->post_title));

        // Display post excerpt
        printf('<div class="related-item__excerpt">%s</div>', wp_kses_post($related_post->post_excerpt));

        printf('</div>');
    }
} else {
    // Display a message when no related content is found
    echo 'No related content found.';
}

To get additional information, watch the video below and read the official ACF article.

ACF Relationship field with code, video cover

Query by Relationship field

When you have the relationship field, we can obviously display the selected relationship items in the current post. Besides that, we can also create the ACF Relationship query and find all the posts where the current one is added as an item in the relationship field, which is very useful.

Note: Starting from version 6.2, there are two approaches available for achieving this: using WP_Query or utilizing the new Bidirectional feature. The former offers greater flexibility, whereas the latter is simpler to use. When selecting your preferred method, keep in mind that the second option is suitable only for newly created fields. If you already have multiple items with existing data, then opting for the WP_Query approach is advisable. Otherwise, you'll need to repopulate the fields to enable the feature to function correctly.

Using WP_Query

a) Making WP_Query using Smart templates

Advanced Views Pro takes the querying of posts by Relationship and Post Object fields to a new level, allowing users to achieve this without any hassle, thanks to the Cards, and their meta filters. You can see the feature overview below.

How to Display posts & their ACF fields using the meta filter - the image cover of the video overview

Let's walk through an example to demonstrate how easy it is to use Advanced Views Pro for our purpose. Imagine you have a custom post type (CPT) called "Company" and another CPT called "Employee." Each Employee post has a Relationship field that allows selecting the current Company they belong to. The goal is to create a card for the Company CPT that displays all the Employees associated with that Company.

Step-by-step guide

Here's a step-by-step guide on how display all Employees for a Company, using Advanced Views Pro:

  1. Create or open an ACF Card that will be used to query posts by the Relationship/Post Object field.
  2. Create a new Meta Rule and select the target Relationship/Post Object field. Set the Comparison setting to 'Equal.'
    • Use the special $post$ value if you're going to paste the Card shortcode on a Page or Post. The $post$ value will be replaced with the ID of the Page or Post where you've pasted the shortcode. This way, the query will find all Posts where the Relationship/Post Object field contains the current post's ID as the selected value. In our Company example, this perfectly fits the purpose of displaying all Employees on the Company CPT page.
    • Use the numeric ID of the target Post if you want to query all posts that have a specific Post selected in their Relationship/Post Object field, but that specific Post is different from the Page where you're going to paste the shortcode. In this case, you must define the numeric ID of that specific Post. This can be useful, for instance, if you want to display all Employees for a specific Company CPT on the homepage or another page.
    • Use the Relation field alias, i.e., $post$.your-field, to find all posts that have the same option selected as the current page. If the current page field contains multiple values, it will retrieve posts where at least one matches.
  3. Save the ACF Card, and paste the Card shortcode in the target place, where you want to display the related posts.
ACF Views usage. Query by the Relationship field to display a grid of companies, where the current Employee has worked.
Example usage. Query by the Relationship field to display a grid of companies, where the current Employee has worked.
Example of ACF Views usage. Query by the Relationship field to display a list of related datasheets.
Example usage. Query by the Relationship field to display a list of related datasheets.

Summary

That's it! With Advanced Views Pro, you can easily create complex queries based on the Relationship and Post Object fields without worrying about the underlying code. The plugin handles the necessary tricks, like wrapping values in quotes and using 'Like' for comparison, making it effortless to work with all field options for Single, Multiple select, and all return formats of a field.

Advanced Views Pro empowers users to showcase their related posts in various ways, offering a seamless experience to make the most of the ACF Relationship and Post Object fields.

b) Making WP_Query using code

This option requires your knowledge of the WP_Query arguments, along with ACF field types and return formats. But for sure, besides complexity, it also brings more flexibility.

Let's review it on the Team and Project example. In this example, we have two custom post types: "Team Members" and "Projects." We want to establish a relationship between these two post types using the ACF Relationship Field. Each team member can be associated with multiple projects, while each project can have multiple team members working on it. In this way we can make the reverse WP_Query for Projects associated with a Team member:

<?php
// Assuming we are in the single-team-member.php template file

// Get the current team member post ID
$team_member_id = get_the_ID();

// Arguments for the reverse WP_Query
$args = [
    'post_type' => 'projects',
    'meta_query' => [
        [
            'key' => 'team_projects', // Replace 'team_projects' with the ACF Relationship Field name
            'value' => '"' . $team_member_id . '"', // Wrap the value in double quotes to match serialized data
            'compare' => 'LIKE',
        ],
    ],
    'posts_per_page' => -1, // Set to -1 to retrieve all related projects
    'post_status' => 'publish', // Retrieve only published projects
];

// Execute the reverse WP_Query and get the posts
$related_projects_query = new WP_Query($args);
$related_projects = $related_projects_query->get_posts();

// Check if there are related projects
if (!empty($related_projects)) {
    printf('<h2>Projects associated with this team member:</h2>');
    printf('<ul>');
    foreach ($related_projects as $project) {
        $project_title = get_the_title($project->ID);
        $project_permalink = get_permalink($project->ID);
        printf('<li><a href="%s">%s</a></li>', esc_url($project_permalink), esc_html($project_title));
    }
    printf('</ul>');
} else {
    echo 'This team member is not associated with any projects.';
}

To get additional information, watch the video below and read the official ACF article.

ACF Relationship query with code, video cover

Using the bidirectional feature

How the feature works

The task of querying posts that have a relationship with the current one is so common that the ACF plugin developers have introduced a dedicated feature to address this scenario. How does it work?

Let's illustrate this with an example involving Company and Employee custom post types (CPTs). A company can have multiple employees, which is represented by a 'Employees' Relationship field in the Company CPT. This part is fairly straightforward.

Now, let's delve into the task itself. We aim to retrieve a list of all companies where the current employee is associated. With the introduction of the Bidirectional feature, we can achieve this without creating a custom WP_Query. Here's how:

  1. Create a New Relationship Field:
    Add another Relationship field, perhaps named 'Companies', to the Employee CPT.
  2. Enable Bidirectional Relationship:
    Go to the 'Employees' Relationship field, and enable the Bidirectional feature. Set the target field as the new 'Companies' field.

With these steps completed, ACF will now automatically track changes. When you update the 'Employees' Relationship field, ACF will automatically update the related company in the associated employee's 'Companies' field.

This approach allows you to always obtain an up-to-date list of the companies associated with each employee, just like the value of the original relationship field.

Pro tip: You can take it a step further by enabling the Bidirectional feature for the 'Companies' Relationship field as well. This way, any additions or removals of companies on the employee's side will be automatically mirrored on the company's side too.

ACF Company Group with the Bidirectional Employees Relationship
Company Group with Bidirectional Employees Relationship. ACF will automatically add or remove the current Company from the target field when you add or remove an Employee.
ACF Company Group with the Bidirectional Employees Relationship
Employee Group with Bidirectional Companies Relationship. ACF will automatically add or remove the current Employee from the target field when you add or remove a Company.

How to display values from the bidirectional field

Displaying values from the Bidirectional field doesn't differ from working with a regular field. You can follow the instructions in the 'Display Relationship Field' chapter of this article to showcase the selected items. The significant advantage is that you can now interact with the field directly, eliminating the need for any WP_Queries.

Important note about existing fields

Enabling the feature doesn't automatically update the related fields. It merely activates the monitoring and automatic updating going forward. Consequently, if you already have items with filled data, they won't automatically appear in the target field. Even pressing 'Update' for the items won't trigger this behavior, as ACF specifically tracks changes in the fields, such as additions or removals of items. Therefore, if you intend to employ this feature for pre-existing items, you will need to repopulate the fields or resort to the WP_Query approach.

Conclusions

In conclusion, the ACF Relationship field is a powerful tool that allows you to establish connections between different content types in WordPress. By using this field, you can create meaningful relationships between posts, pages, custom post types, and more, making it easier to manage and display related content on your website.

With the ACF Relationship field, you can build advanced and flexible data structures, enabling you to create complex relationships between various content elements. This opens up endless possibilities for organizing and presenting content on your WordPress site.

We explored how to display the ACF Relationship field both using manual coding and Smart templates from the Advanced Views framework. Advanced Views gives you full control and customization options, along with a user-friendly interface, that helps to display related content. The Advanced Views Pro version takes it a step further, offering enhanced capabilities to query and display related content, providing users with a seamless and efficient experience.

Whether you're building a portfolio site with connections between projects and team members, or a real estate website with property listings and agents, the ACF Relationship field can significantly improve the organization and presentation of your content.

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

FAQ mode

/

Learning mode

  1. What is the purpose of the ACF Relationship field?

    The ACF Relationship field serves to establish connections between different post types or custom post types, enabling users to create meaningful relationships between various content elements on their WordPress websites.

  2. How does the ACF Relationship field differ from the Post Object field?

    While both fields serve similar purposes, the ACF Relationship field offers more advanced filtering options and bidirectional linking, making it ideal for scenarios involving many-to-many relationships and interconnected content.

  3. How are relationships stored in the database with the ACF Relationship field?

    Relationships are discreetly stored as post meta, allowing ACF to manage connections between content elements without altering the original content structure.

  4. How can I query content based on established relationships?

    You can utilize the WP_Query function, leveraging the meta_query parameter to filter posts by their post meta values, retrieving content based on the relationships established with the ACF Relationship field.

Course navigation: ACF Plugin

Content links (35)

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