
Hello, I have an Address post_type that is connected to Post using a relationship field. I wonder if it’s possible to pre-select the address in the relationship field when I create a new Post. The id of the address would come through a query param (not sure if there’s a better way but this allows us to create simple links from another system). I only need a single Address to be associated to the post.
I tried with acf/load_value
but that didn’t work. I can see the function is called and the $post_id and $field are correct, but returning an array doesn’t seem to populate the field in the form. Here’s the code:
function setAddress($value, $post_id, $field) {
$addressId = $_GET['address_id'] ?? false;
if ($addressId) {
return [$addressId];
}
return $value;
}
add_filter('acf/load_value/name=address', 'setAddress', 10, 3);
Is this something that can be done in a new post or does it only work when updating existing posts?
The return format I selected is Post Object. If I try to return an array of post objects (return [get_post($addressId)];
) the ACF field doesn’t show up so that doesn’t seem to be it.
Maybe there’s an alternative way I’m not aware of?
I got it working now! I think the problem was that I wasn’t casting the id to an int. I changed it and added a check to make sure we are looking at a new post:
public static function setAddress($value, $post_id, $field): mixed
{
$post = get_post($post_id);
// Check we are on the new screen
if ($post->post_status === 'auto-draft') {
$address_id = $_GET['address_id'] ?? false;
if ($address_id) {
$value = [(int) $address_id];
}
}
return $value;
}