wordpressrelationshipadvanced-custom-fields

Not showing results from a get_posts meta_query using ACF Relationship field


I am trying to show related services through my single-services.php template. I have used the ACF relationship field. When I print_r the field data, it all works. However, when I try to call specific fields into my layout with meta_query, it doesn't work and I can't see why.

     $related_services = get_posts(array(
          'post_type' => 'services', // name of custom post type
          'meta_query' => array(
              array(
                  'key' => 'related_services', // name of custom field
                  'value' => '"' . get_the_ID() . '"',
                  'compare' => 'LIKE'
              )
          )
      ));
    if( $related_services ):
       foreach( $related_services as $related_service ):
          $icon = get_field('service_icon', $related_service->ID);
          echo $icon; 
     endforeach;
   endif; 

Solution

  • The main issue likely lies in how you're trying to query the relationship field using meta_query with compare => 'LIKE'.

    <?php
    $related_services_objects = get_field('related_services'); 
    
    if ( $related_services_objects ): ?>
        <div class="related-services-list">
            <h3>Related Services</h3>
            <ul>
                <?php foreach ( $related_services_objects as $related_service ): 
                    $post_id = $related_service->ID;
                    $title = get_the_title($post_id);
                    $permalink = get_permalink($post_id);
                    $icon = get_field('service_icon', $post_id);
                    ?>
                    <li>
                        <a href="<?php echo esc_url($permalink); ?>">
                            <?php if ($icon): ?>
                                <img src="<?php echo esc_url($icon['url']);  ?>" alt="<?php echo esc_attr($icon['alt']); ?>">
                            <?php endif; ?>
                            <?php echo esc_html($title); ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php
        
    endif;
    ?>