Customise the post titles in ACF’s relationship field

If you’ve ever found yourself wanting to modify the post titles in an ACF relationship field, you may have already stumbled across the acf/fields/relationship/result filter. It’s a pretty useful filter when you want to provide some more contextual information next to a post title in the relationship field results list.

As with many filters built into Advanced Custom Fields, it provides some useful variations that allow us to target specific fields by either their field name or their field key.

Adding a human-readable age to the post title, as an example

This is just one simple example of what we can pull off using this filter and some of WordPress’ built-in utility functions. Keep in mind that I’m targeting a specific field by name (related_posts) here:

<?php
add_filter( 'acf/fields/relationship/result/name=related_posts', function ( $title, WP_Post $post, $field_arr ) {
$posted_at = get_post_time( 'U', false, $post->ID );
$now = current_time( 'timestamp' );
$diff = human_time_diff( $posted_at, $now );
return $title . sprintf( ' (%s ago)', $diff );
}, 10, 3 );

With the above snippet in place, you’ll end up with something like the following in the WordPress admin:

An ACF relationship field with the age of each post against the titles.
Adding contextual information can make the end-users life that little bit sweeter when interacting with Advanced Custom Fields.

What’s really nice about this filter is that you’ll have access to the WP_Post object as well as the ACF field array so you have a lot of information at your fingertips to format those post titles in the most sensible way possible.

I definitely recommend checking out the ACF documentation on this filter to learn more.

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.