wp-graphql / wp-graphql-acf

WPGraphQL for Advanced Custom Fields
https://wpgraphql.com/acf
626 stars 124 forks source link

Where condition for ACF doesn't work....??? #377

Closed codyng closed 8 months ago

codyng commented 9 months ago

Hi there,

I have made a query for a custom post types such as: courses (single name: course, plural name: courses) and ACF is registered to the type.

Also the course has a category field with "Relationship" ACF type.

While it is fine to query a list of courses:

{
  courses {
    nodes {
      slug
      title
      course {
        category {
           ... on Category {
               slug
           }
        }
        level
      }
    }
  }
}

However, if I apply the where condition to the query, it doesn't work:

{
  courses(where: { course: { category: { slug: "some-slug" } } }) {
    nodes {
      slug
      title
      course {
        category {
           ... on Category {
               slug
           }
        }
        level
      }
    }
  }
}

It throws the error: "Field \"course\" is not defined by type RootQueryToCourseConnectionWhereArgs."

Doesn't the plugin automatically add the appropriate types for query where condition?? Or how to solve that in such the query coz I would like to query by the category slug?

Many thanks!!!

jasonbahl commented 8 months ago

@codyng since you're querying the field courses you don't need to nest course as a field of the where args.

And to query by category, you need the categoryId.

I've used ACF to register a Custom Post Type named "Courses" and I added support for the "category" taxonomy with this PHP:

add_action( 'init', function() {
    register_taxonomy_for_object_type( 'category', 'course' );
});

Then I added 2 posts, 1 assigned to a category and 1 not assigned to a category:

CleanShot 2024-01-08 at 11 20 58

Then I was able to query them, filtered by categoryId with the following query:

query GetCoursesByCategoryId {
  courses(where:{categoryId: 25}) {
    nodes {
      id
      title
      categories {
        nodes {
          id
          databaseId
          name
        }
      }
    }
  }
}

CleanShot 2024-01-08 at 11 20 51

jasonbahl commented 8 months ago

Hey @codyng, there is a new version of WPGraphQL for ACF we recommend checking out when you have a chance. https://wordpress.org/plugins/wpgraphql-acf/

It's a complete re-architecture and solves a lot of issues. This repo will be archived in the not-too-distant future.