Skip to content
Advertisement

How do you query a custom post type (CPT) via an ACF relationship field?

Overview

I have two CTPs:

  1. Range: Which showcases 4 van types
  2. Wheels Which showcases all wheels a van can have.

In the wheels post type, I have two ACF fields:

  1. Image: Which is of type image (an image of the wheel). The name of this field is image
  2. Available on: Which is a relationship field where we can select which vans (from the range post type) this wheel is available on. The name of this field is available_on_range

Now, I’m querying range by id for each page and want to pull in all of the wheels that have this range in its relationship field.

For example, allow wheel 7 is available on range/van 1, but not on range/van 4.

Current problem

My relationship field is working, as I’m able to get and output the wheel name (post_title), however, I can’t seem to get the image for that wheel (no src).

Code

JavaScript

A var_dump($wheel_image) returns NULL.

How can I get the image?

Have also tried

  • <img src="<?php echo the_field('image'); ?>" alt="<?php echo $wheel_name; ?>" loading="lazy"/>
  • <img src="<?php echo esc_url($wheel_image['url']); ?>" alt="<?php echo $wheel_name; ?>" loading="lazy"/>

A var_dump($wheel) doesn’t show anything related to the image:

JavaScript

Which means that there is an issue with my $related_wheels query. But, I only want to query wheels that match the id of the current page, which is what the query currently does. How do I make it show the image data also?

Advertisement

Answer

Please change the get Image field like this. The type of $wheel is object, so you couldn’t use the method of getting value of array.

JavaScript

Then you can add image url to the Image tag.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement