Home Forums Front-end Issues Show field from relationship


Show field from relationship

  • Hi all,

    I checked the documentation, forum threads and tried Google. I guess the answer is too simple so that it’s not written anywhere. Or I am just stupid…

    The setup

    I have 2 custom post types: companies, ads

    Companies has a post_title which is the company’s name and a logo (ACF image upload)

    Ads has besides a post_title two ACF fields which are file upload and company name (relationship)

    The question

    On my ads-single.php I can output the file upload easily by using <?php the_field('ad_image'); ?>

    I want to display the company’s name (relationship) next to it. It gives me back an array. I need to get the post_title and the logo from that array.

    I tried this:

    $company = get_field('company');
    $company_name = $company['post_title'];
    echo $company_name;

    It doesn’t work.

    Any ideas? I just need to pick fields from 2 post types that are related to each other. It’s also just a 1:n relationship.

  • The result of the relationship field is going to be an array of pages, even if only one is selected. So you would either need to loop through them or target the array index. Furthermore the result of each item in the array is an object.

    The loop would be:

    $companies = get_field('company');
    foreach($companies as $company){
         $company_name = $company->post_title;
         echo $company_name;

    To target the first relationship in the array:

    $companiy = get_field('company');
    $company_name = $company[0]->post_title;
    echo $company_name;
  • Thanks, this worked for me!

    Although I ignored the typo I can’t address $company[0] – nothing will echo. But as I always just have 1 it worked fine with the first part.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Show field from relationship’ is closed to new replies.