skip to Main Content

I use ACF to built a theme for my hiking blog… To be short each Hike(CPT) can have many Summit(CPT) and each Summit(CPT) has 1 Location(CPT).

When I add a Hike, i can add 1 or many summit in the box. That part work great. But for example if in one Hike i’ve had to choose Black Mountain, i face off with multiple "Black Mountain" choice without knowing which one is the good. I would like to show the location next to the Summit Name.

What I’ve so far

 add_filter('acf/fields/relationship/result/name=sommet_rel', 'id_relationship_result', 10, 4);
function id_relationship_result($title, $post, $field, $post_id){
 
    $location = get_field('location', $post->ID);
    $title.= ' ' .  $location->$post_title;
    
    return $title;
} 

My structure

Hike ( Custome Post Type)

  • Summit (Bi-directionnale relationship)

Summit (custom Post Type)

  • Hike (Bi-Directionnale relationship)

  • Location (Relationship)

Location (Custom Post Type)

I know that for the filter i’m in the good place because when I put some hard coded values it’s ok… But there’s is now way to dig into the relationship.

I’ve try to var_dump many value with no success.

I’m lost on this one and there is very little information on the net about this filter.

enter image description here

I’m lost on this one and there is very little information on the net about this filter.

2

Answers


  1. I see what you’re trying to do. You want to show the location alongside the summit name in the relationship field to differentiate between multiple summits with the same name.

    Your code is almost there, but there’s a minor error. You’re attempting to access the $post_title property of the $location object, which isn’t correct. Instead, you should use get_the_title($location->ID) to retrieve the title of the location post.

    add_filter('acf/fields/relationship/result/name=sommet_rel', 'id_relationship_result', 10, 4);
    function id_relationship_result($title, $post, $field, $post_id){
        $location = get_field('location', $post->ID);
        $title.= ''. get_the_title($location->ID). ')';
        return $title;
    }
    
    Login or Signup to reply.
  2. @F.Soucy,

    Thanks for your effort! I saw your issue and I experimented locally. I found the solution!

    Here is the updated code:

    add_filter('acf/fields/relationship/result/name=sommet_rel', 'id_relationship_result', 10, 4);
    function id_relationship_result($title, $post, $field, $post_id){
        $location = get_field('location', $post->ID);
        $title .= " (".$location[0]->post_title.")";
        return $title;
    }
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search