wordpressgraphqladvanced-custom-fieldsacfprowp-graphql

Possible to return ACF fields from Post Object or Relationship type?


I have an ACF field group named Product Type. It contains a few very simple fields such as part_number (text), store_url (URL), and description (text). This field group is only displayed for posts, and I have the "Show in GraphQL" field toggled on.

Next I created a new post, where I filled in these fields and published them.

After that, I modified an existing field group that is displayed for a page, so that it returns a Post Object type. I then went into the related page, selected the new post I'd created, and saved. As far as I can tell, everything is hooked up fine here.

The problem I'm facing is that I'm unable to query these new fields of either a Post Object or Relationship in my GraphiQL editor. I'd assumed that by selecting that new post when editing my page, (and setting its return type to the Post object and not just the ID), that it'd return those new ACF fields as well but that doesn't seem to be the case.

fragment ProductType on Page_Productslug_tables_tableImages_Product {
  __typename
  ... on Post {
    id
    partNumber <-- new ACF field
  }
}

query GetProductSlug($id: ID!) {
  page(id: $id, idType: URI) {
    page: productSlug {
      tables {
        tableImages {
          anchorId <-- previous ACF field that still works
          product {
            ...ProductType
          }
        }
      }
    }
  }
}

This just returns "Cannot query field \"partNumber\" on type \"Post\".", but I've tried all sorts of variations of fragments and queries.

My uneducated guess is that the schema is generating product as a union type of Page_Aluminumframingslug_tables_tableImages_Product which only has one possible type of Post, but Post can only return normal Post properties internal to Wordpress, and not ACF fields.

So how can I go about returning ACF fields for a nested relationship?


Solution

  • For posterity, in my case it didn't involve creating a custom register_graphql_field or anything like I originally thought. It took a lot of digging through the generated graphql schema, but I came up with this fragment to use, and things seem to be working well.

    fragment Product on Post {
      productType {
        partNumber
        image {
          ...Image
        }
        pdf {
          mediaItemUrl
        }
        storeUrl
        description
      }
    }
    

    This fragment contains all of the custom ACF fields I'd created for a Post, and when selecting a Post Object to attach to a Page, it creates a union type (one of which in my case is Post).